Given the code fragment:
public class Test {
public static List data = new ArrayList();
// insert code here
{
for (String x : strs) {
data.add(x);
}
return data;
}
public static void main(String[] args) {
String[] d = {"a", "b", "c"};
update(d);
for (String s : d) {
System.out.print(s + " ");
}
}
}
Which code fragment, when inserted at // insert code here, enables the code to compile and and print a b c?
A.
List update (String[] strs)
B.
static ArrayList update(String[] strs)
C.
static List update (String[] strs)
D.
static void update (String[] strs)
E.
ArrayList static update(String[] strs)
题解
题目原先提供的程序,第 7 行的 strs 会因为没有声明而编译错误。第 10 行的 return 会因为目前程序区块不是可以回传 List 对象的方法而编译错误。第 15 行会因为找不到 update 方法而编译错误。
为了解决编译错误的问题,必须要在第 5 行完成方法的声明。方法的名称叫作「update」,因为要可以直接在 main 方法中使用,所以一定是类别静态(static)方法,要用 static 修饰。update 方法只能接受字符串数组参数的传入,所以要设置一个字符串数组的参数,至于参数名称可以从第 7 行知道,就是「strs」这个变量名称。第 10 行需要回传 List 对象,所以 update 方法的回传值型态应该要声明成 List 或是 List 的父类别型态。
选项 A、B、D、E 都不符合要求,只有选项 C 是正确的。
