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 变量的值,因此编译时会有无法找到变量的错误。