acessing variabloe outside loop
Hello,
I have a programming assignment ive spent the better part of today working and I am having some trouble. I have to make a program that reads data from a text document containing employee information. After the information on the file is read the hours variable has to be added up. I cannot figure out how to get the hours to add up though. This is what I have so far.
Code Java:
while(inputFile.hasNext())
{
hours = inputFile.nextInt();
rate = inputFile.nextDouble();
name = inputFile.nextLine();
System.out.print(name);
System.out.print(rate);
System.out.println(hours);
}
This whileloop reads all the data in the text document and and prints it out on the screen. But when I try to add a totalHours variable inside the loop it prints out on every iteration of the loop. When I try to add a totalHours variable outside the loop it says the hours variable has not yet been declared. So how would I get the program to add up all the hours then print the total only once? Please help!
Re: acessing variabloe outside loop
If I understand correctly, you want a integer value from a String, from which you can add up. Use either the wrapper class for the number primitive you need, for example Integer.parseInt, to get that number value
Code :
String value = "123";
int intValue = 0;
try{
intValue = Integer.parseInt(value);
}catch(NumberFormatException e){
e.printStackTrace();
}
Re: acessing variabloe outside loop
Re: acessing variabloe outside loop
@copeg: Don't nextInt() extracts integer from the string and casts it to integer datatype?
Re: acessing variabloe outside loop
Quote:
Originally Posted by
Mr.777
@copeg: Don't nextInt() extracts integer from the string and casts it to integer datatype?
Thanks for the correction