Given:



public class TestLoop {

    public static void main(String[] args) {
        int array[] = {0, 1, 2, 3, 4};
        int key = 3;
        for (int pos = 0; pos < array.length; ++pos) {
            if (array[pos] == key) {
                break;
            }
        }
        System.out.print("Found " + key + " at " + pos);
    }
}

What is the result?

A. Found 3 at 2
B. Found 3 at 3
C. Compilation fails
D. An exception is thrown at runtime

題解

這題的程式會編譯錯誤,因為pos變數是在for迴圈內被宣告的,但是程式第11行卻要去取得pos變數的值,因此編譯時會有無法找到變數的錯誤。