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」字符转成大写后的结果。
