Given:



public class MyClass{
    public static void main(String[] args){
        while(int ii = 0; ii < 2){
            ii++;
            System.out.println("ii = " + ii);
        }
    }
}

What is the result?

A.

ii = 1
ii = 2

B. Compilation fails
C. The program prints nothing
D. The program goes into an infinite loop with no output
E. The program goes to an infinite loop outputting:

ii = 1
ii = 1

題解

此題的while迴圈用法錯誤,會造成編譯錯誤。如果要修正,可以改寫成:

public class MyClass{
    public static void main(String[] args){
        int ii = 0;
        while(ii < 2){
            ii++;
            System.out.println("ii = " + ii);
        }
    }
}

或是使用for迴圈改寫成:

public class MyClass{
    public static void main(String[] args){
        for(int ii = 0; ii < 2;){
            ii++;
            System.out.println("ii = " + ii);
        }
    }
}