Reputation: 249
I am just beginner at programming and I just started taking java at our school last week. What I am trying to do is skip an iteration using continue statement in while loop in java and unfortunately the output is not what I expected it to be...
This is my code:
// Using while Loop
int counter = 1;
while(counter <= 5){
if(counter == 3){
continue;
}
System.out.println(counter);
counter++;
}
The output is: 1 2 and it doesn't print the 4 and 5 but I've noticed that the program is still not terminated.
I've even tried coding it like this:
int counter = 1;
while(counter <= 5){
System.out.println(counter);
if(counter == 3){
continue;
}
counter++;
}
It just prints 3 nonstop
int counter= 1;
while(counter <= 5){
counter++;
if(counter == 3){
continue;
}
System.out.println(counter);
}
this one prints 2 4 5 6 instead of 1 2 4 5
I have used for loop to do this and it work well
this is my code:
//using for loop
for(int counter = 1; counter <= 5; counter++){
if(counter == 3){
continue;
}
System.out.println(counter);
}
this prints the right output...
Now, can anyone please tell me what is my mistake in using while loop in doing this exercise? Thanks...
Upvotes: 2
Views: 3009
Reputation: 481
By the way, in first answer given by @GBlodgett, you know why your program is not showing the result you were expecting. This is how you can achieve your result.
// Using while Loop
int counter = 0;
while(counter < 5){
counter++;
if(counter == 3){
continue;
}
System.out.println(counter);
}
Upvotes: 1
Reputation: 1195
The issue is that once counter == 3, it will always hit the if statement as true and never increment counter again. So your while loop will print 1 2 and then execute infinitely.
In order to solve the issue, code it like this:
// Using while Loop
int counter = 1;
while(counter <= 5){
if(counter == 3){
counter++;
continue;
}
System.out.println(counter);
counter++;
}
Just add counter++ before your continue statement. Hope this helps.
Upvotes: 1
Reputation: 12819
if(counter == 3){
continue;
}
System.out.println(counter);
counter++;
Here the continue
statement skips the ctr++;
statement, so it is always 3
and the while
loop never terminates
int counter = 1;
while(counter <= 5){
System.out.println(counter);
if(counter == 3){
continue;
}
counter++;
}
Here the print statement will be reached, as it is before the continue
statment, but the counter++;
will still be by passed, resulting in an infinite loop of printing 3.
int counter= 1;
while(counter <= 5){
counter++;
if(counter == 3){
continue;
}
System.out.println(counter);
}
Here counter++
is reached, but it will be incremented before the println()
so it prints out one plus the values you want
Upvotes: 3