質問

public class Main {
    public static void main(String [] args) {
        int i = 0;
        do {
           System.out.println(i); 
           i++;
        } while (i==3);
    }
}

// Outputs 0

Why do iterations stop at zero? while(i==3) is a condition, which tests for equality of i to 3. But then, even after incrementing the value of i as i++ why the output is only 0?

役に立ちましたか?

解決 2

Your condition would be i!=3. Change to while(i!=3). You have mistakenly put the wrong condition in the while loop. You have said it to loop the while only when i==3 otherwise to exit the loop. So you need to change it to

  do {
       System.out.println(i); 
       i++;
    } while (i!=3);

Hope this clarifies!

他のヒント

Because it'll print i, which is 0, then will increment it, and won't loop since 3 != 1:

do {
    System.out.println(i); //i is 0, will print 0
    i++;                   //i is now 1
} while (i==3);            //false

Read The while and do-while Statements to better understand how the do-while loop works.

I'm carefully assuming that you meant to write while(i != 3);, if that's the case, your program will loop and will print 0 1 2.

Because you increment after printing.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top