Given:



public class Test3 {

    public static void main(String[] args) {
        String names[] = new String[3];
        names[0] = "Mary Brown";
        names[1] = "Nancy Red";
        names[2] = "Jessy Orange";
        try {
            for (String n : names) {
                try {
                    String pwd = n.substring(0, 3) + n.substring(6, 10);
                    System.out.println(pwd);
                } catch (StringIndexOutOfBoundsException sie) {
                    System.out.println("String out of limits");
                }
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array out of limits");
        }
    }
}

What is the result?

A.

Marrown
String out of limits
JesOran

B.

Marrown
String out of limits
Array out of limits

C.

Marrown
String out of limits

D.

Marrown
NanRed
JesOran

題解

names[0]的長度是10,索引範圍是0~9;names[1]的長度是9,索引範圍是0~8;names[2]的長度是12,索引範圍是0~11。當字串索引範圍不正確的時候會拋出「StringIndexOutOfBoundsException」例外。

程式第11行有用到字串物件的「substring」方法來取的子字串,取得names字串陣列中每個字串的子字串,子字串的字元索引範圍是0~2和6~9,所以長度未滿10的names[1]將會拋出「StringIndexOutOfBoundsException」例外,而其他的字串則可以成功地進行子字串的串接。