Given the fragment:

String[][] arra = new String[3][];
arra[0] = new String[]{"rose", "lily"};
arra[1] = new String[]{"apple", "berry", "cherry", "grapes"};
arra[2] = new String[]{"beans", "carrot", "potato"};
// insert code fragment here

Which code fragment when inserted at line '// insert code fragment here', enables the code to successfully change arra elements to uppercase?

A.

for(int i = 0; i < arra.length; i++){
    for(int j = 0; j < arra[i].length; j++){
        arra[i][j] = arra[i][j].toUpperCase();
    }
}
B.
for(int i = 0;i < 3; i++){
    for(int j=0; j < 4; j++){
        arra[i][j] = arra[i][j].toUpperCase();
    }
}
C.
for(String a[] : arra[][]){
    for(String x : a[]){
        x.toUpperCase();
    }
}
D.
for(int i : arra.length){
    for(String x : arra){
        arra[i].toUpperCase();
    }
}

题解

选项 A,索引值范围和修改数组的方式都是正确的。

选项 B,内循环错误的固定索引范围会使程序抛出 ArrayIndexOutOfBoundsException。

选项 C,for 循环中的「arra[][]」和「a[]」是错误的语法,会造成编译错误。就算改成「arra」和「a」,「toUpperCase」方法也不会直接修改字符串的内容,而是会将修改后的字符串回传,所以这样做是没有效果的。

选项 D 有严重错误的语法,for 循环无法这样使用。