Results 1 to 7 of 7
- 02-28-2009, 04:42 AM #1
Member
- Join Date
- Feb 2009
- Posts
- 13
- Rep Power
- 0
Variable not initialized after while loop
I have some code that contains the variable hoursWorked. My code has the user input the hoursWorked and it functions. Now I want to put this line of code into a while loop to make loop until the entered value is >0. When I do this the variable hoursWorked which is used after this while statement now thinks it isn't initialized after the while statement. Why would adding the while loop make the program think the hoursWorked varialble isn't initialized later on in the code?
- 02-28-2009, 04:46 AM #2
Senior Member
- Join Date
- Sep 2008
- Posts
- 564
- Rep Power
- 5
it would help if we saw your code... and if your variable is an int, i think it's automatically initialized to 0.
- 02-28-2009, 04:47 AM #3
Senior Member
- Join Date
- Dec 2008
- Location
- Hong Kong
- Posts
- 473
- Rep Power
- 5
are you declaring the variable inside the while loop?
- 02-28-2009, 04:48 AM #4
Member
- Join Date
- Feb 2009
- Posts
- 13
- Rep Power
- 0
Added section of code.
double hoursWorked;
double hourlyRate;
double sum;
String employeeName = "null";
while(!employeeName.equals("stop")) {
System.out.println("Enter Employee Name"); //prompt
employeeName = input.nextLine(); //read first number from user
if (employeeName.equals("stop"))
break;
int verify = -1;
while(verify <0) {
System.out.print( "Enter Hours Worked: " ); // prompt
hoursWorked = input.nextDouble(); // read second number from user
if (hoursWorked <0)
System.out.println("Please enter a positive number");
else
verify = 1;
}
System.out.print( "Enter Hourly Rate: " ); // prompt
hourlyRate = input.nextDouble(); // read second number from user
sum = hourlyRate*hoursWorked;
- 02-28-2009, 04:49 AM #5
Member
- Join Date
- Feb 2009
- Posts
- 13
- Rep Power
- 0
No I declare it before the while loop.
- 02-28-2009, 04:55 AM #6
Senior Member
- Join Date
- Dec 2008
- Location
- Hong Kong
- Posts
- 473
- Rep Power
- 5
it is possible that your code may not enter the while loop
hoursWorked may not assign to any value,
i suggest you to initialize it to 0
- 02-28-2009, 05:00 AM #7
Member
- Join Date
- Feb 2009
- Posts
- 13
- Rep Power
- 0
Similar Threads
-
[SOLVED] "start: applet not initialized"
By DenniGa in forum Java AppletsReplies: 3Last Post: 02-24-2009, 02:10 AM -
[SOLVED] Referencing Variable within Loop
By Judoon_Platoon in forum Java AppletsReplies: 2Last Post: 05-22-2008, 11:54 AM -
getting the value of variable
By Lehane_9 in forum New To JavaReplies: 2Last Post: 03-05-2008, 01:42 AM -
Getting variable value from a variable name
By Java Tip in forum Java TipReplies: 0Last Post: 02-16-2008, 09:26 PM -
Not initialized variable
By bbq in forum New To JavaReplies: 2Last Post: 07-04-2007, 09:02 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks