Ibteda Sabur Ibteda Sabur - 3 months ago 7
Java Question

Why does this while loop run after the condition is met?

When I do a regular while loop like this

int x = 0;

while (x < 2) {
System.out.println(x);
x = x + 1;
}


it prints

0
1


but this second while loop runs one more time after the condition is met.

class Hobbits {
String name;

public static void main(String [] args) {

Hobbits [] which = new Hobbits[3];

int number = -1;

while (number < 2) {

number = number + 1;

which[number] = new Hobbits();

which[number].name = "bilbo";

if (number == 1) {
which[number].name = "frodo";
}

if (number == 2) {
which[number].name = "sam";
}

System.out.print(which[number].name + " is a ");
System.out.println("good Hobbit name");

}
}
}


so the result is

bilbo is a good Hobbit name
frodo is a good Hobbit name
sam is a good Hobbit name


shouldn't it stop printing at "frodo is a good Hobbit name"

I set the condition for x < 2 so how does "sam" print if the while loop was supposed to stop at x == 1?

Edit: ohhh I get it now lol I was thinking like the increment was at the end of the code and the start was 0

Answer

There's nothing wrong in that behaviour. You set number = -1 and then you do a loop that will iterate while number < 2. So, -1, 0 and 1. Three iterations. What's the problem? Let's do a simple trace:

number = -1
(-1 < 2)? Yes. Execute code inside while.
number = number + 1 (0)
(0 < 2)? Yes. Execute code inside while.
number = number + 1 (1)
(1 < 2)? Yes. Execute code inside while.
number = number + 1 (2)
(2< 2)? No. Continue with the next instruction after the while block.