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
String out of limits
JesOran
B.
Marrown
String out of limits
Array out of limits
String out of limits
Array out of limits
C.
Marrown
String out of limits
String out of limits
D.
Marrown
NanRed
JesOran
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」例外,而其他的字串則可以成功地進行子字串的串接。
