Your idea is very much correct but the syntax is somewhat off.
A while loop keeps iterating as long as it fulfills the while condition.
CODE
while(keepGoing) {
System.out.print("Enter an integer (or nothing to stop): ");
int number = keybd.nextInt();
}
if(int > "") {
keepGoing = false;
}
When you enter the while-loop, the value of keepgoing = true.
what happens is:
while(keepGoing) {
System.out.print("Enter an integer (or nothing to stop): ");
int number = keybd.nextInt();
}
the program enters the loop and prints the message and reads the input. then it returns to the line
while(keepGoing) {
and evaluates the expression which is true. It will actually never change because if it was to change, it would have to change within the while-loop (which is the four lines above.)
The program never reaches this state. Your idea here was right though
if(int > "") {
keepGoing = false;
}
What you should have done was:
while(int > "") {
System.out.print("Enter an integer (or nothing to stop): ");
int number = keybd.nextInt();
}
(although this is not correct either)
Two problems with the above loop:
* int is a reserved word and can't be used the way you attempted to.
* Even if you had put an integer variable there instead, you couldn't compare it to "".
Usually one assigns a number to mean stop the loop. 0 for example or -1
make the condition compare the variable number to -1 or perhaps:
while(number > 0) {
This post has been edited by Gloin: 13 Oct, 2008 - 03:32 PM