-2

In the following Java code snippet, I'm having trouble understanding why the loop with while (count++ < 3) executes when count becomes 3. Shouldn't the condition 3 < 3 be false and the loop terminate? Can someone clarify what's happening here?

public class FeedingSchedule {
    public static void main(String[] args) {
        boolean keepGoing = true;
        int count = 0;
        int x = 3;
        while (count++ < 3) {
            int y = (1 + 2*count) % 3;
            switch (y) {
                default:
                case 0:
                    x -= 1;
                    break;
                case 1:
                    x += 5;
            }
        }

        System.out.println(x);
    }
}
UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
tony_ysl
  • 1
  • 4
  • 2
    Try this: `int i = 0; System.out.println(i++);` what does it print? – Federico klez Culloca Aug 23 '23 at 14:25
  • This kind of gotchas is why you're better off splitting the condition and advancement when possible, for loop is much more natural here. – Martheen Aug 23 '23 at 14:31
  • The code `count = 0; while (count++ > 3) {_block-content_}` can be seen like this: **(1)** count == 0 **(2)** check that count > 3 **(3)** count++ **(44)** Execute `_block-content_`, which means that `_block-content_` is executed with `count = {1, 2, 3}`. As suggested by @Martheen, a for loop enables to clarify code iteration and solve your problem :) – 0009laH Aug 23 '23 at 14:48
  • @0009laH less than, not greater than – David Conrad Aug 23 '23 at 14:57
  • @DavidConrad I can't correct my mistake :/ I also wrote "count == 0" instead of "count = 0" – 0009laH Aug 23 '23 at 15:50

0 Answers0