Given:
public class TestTry {
public static void main(String[] args) {
StringBuilder message = new StringBuilder("hello java!");
int pos = 0;
try {
for (pos = 0; pos < 12; pos++) {
switch (message.charAt(pos)) {
case 'a':
case 'e':
case 'o':
String uc = Character.toString(message.charAt(pos)).toUpperCase();
message.replace(pos, pos + 1, uc);
}
}
} catch (Exception e) {
System.out.println("Out of limits");
}
System.out.println(message);
}
}
What is the result?
A.
hEllO jAvA!
B.
Hello java!
C.
Out of limits
hEllO jAvA!
hEllO jAvA!
D. Out of limits
題解
第 4 行的字串為「hello java!」,共有 11 個字元,可知字串長度是 11。
第 7 行開始的 for 迴圈,pos 變數的值為 0,1,2,3,...,11,迴圈會執行 12 次。
第 8 行開始的 switch,會在每次迴圈執行的時候把字串中對應位置的字元「a」、「e」、「o」轉成大寫。但是當 pos 變數為 11 的時候,第 8 行會因為要取得的字元索引位置超過字串本身的長度而拋出例外,例外會在第 16 行開始被接住,而先輸出「Out of limits」。
最後,第 19 行才會輸出將「hello java!」中所有的「a」、「e」、「o」字元轉成大寫後的結果。
