Reputation: 13
I've noticed when using while loops in my java programs that when using a boolean type to terminate it does not seem to be working. I typed up something simple to test it. The code completes through i = 9 and then test is printed out as false.
public class LoopTesting {
public static void main(String[] args) {
boolean test = true;
while(test) {
for (int i = 1; i < 10; i++) {
System.out.println(i);
if(i == 5) test = false;
}
}
System.out.println(test);
}
}
EDIT: In response to afzalex's answer I tested this code:
while(test) {
for (int i = 1; i < 10; i++) {
System.out.println(i);
}
test = false;
for(int i = 11; i < 20; i++) {
System.out.println(i);
}
}
and it prints to 19.
Upvotes: 1
Views: 8057
Reputation: 10433
Here is how you second question code looks like if you replace while and for with a simple if/goto. Maybe this is easier to understand for you:
loopA: // while
if (test) {
int i1 = 1;
loopB: // for 1
if (i1 < 10) {
System.out.println(i1);
i1++;
goto loopB;
}
test = false;
int i2= 11;
loopC: // for 2
if (i2 < 20) {
System.out.println(i2);
i2++;
goto loopC;
}
goto loopA;
}
System.out.println(test);
Upvotes: 0
Reputation: 8680
You have an error in your logic. The test
variable isn't getting checked until your inner for-loop completes. If you only want to iterate 5 times, you can do this:
while(test) {
for (int i = 1; i < 10; i++) {
System.out.println(i);
if(i == 5){
test = false;
break;
}
}
}
But you probably want to do something like this:
...
int i = 1;
while(test) {
if(i == 5)
test = false
else i++;
}
Upvotes: 0
Reputation: 2037
The issue with your while
loop not closing is because you have an embedded for
loop in your code. What happens, is your code will enter the while
loop, because while(test)
will result in true
. Then, your code will enter the for
loop. Inside of your for loop, you have the code looping from 1-10. This loop is based off of the Integer
value i
. The inside loop is basically saying while(i < 10)
, so this inside loop is not effected by the boolean
value of test.
while(test) { // This loop will continue to run until test == false
for (int i = 1; i < 10; i++) { // This loop will continue to run until i > 9
test = false; // This will execute on the first loop of the inner loop, but it is not checked at the outer loop until the inner loop is complete
}
}
Hope that makes sense. Your issue is that the boolean is corresponding to the outer loop, nothing is stopping the inner loop from running.
Upvotes: 1
Reputation: 35106
This is what you want
while(test) {
for (int i = 1; i < 10; i++) {
System.out.println(i);
if(i == 5) {
test = false;
break;
}
}
}
or more simply
int i = -1;
while(test) {
i++;
System.out.println(i);
if(i == 5) {
test = false;
}
}
Upvotes: 4
Reputation: 8652
You changed test
value inside for loop. but condition for for
loop is i < 10
, not test
.
So for
loop go on iterating until it ends.
Then while is terminated as you had set test
as false
when control was inside for
loop.
Upvotes: 6