寻找下列代码错误public void copy(String[] a, String[] b, String ending) { int index; String temp = null; System.out.println(temp.length()); int length = a.length; for (index = 0; index&a.length; index++) { if (true) { if (temp == ending) { break; } b[index] = temp; } } } }
时间: 2023-03-22 07:01:05 浏览: 81
这段代码中有一个错误,即在调用temp.length()方法之前,temp被赋值为null,因此会抛出NullPointerException异常。应该在赋值temp之后,再进行长度的计算。正确的代码如下:
public void copy(String[] a, String[] b, String ending) {
int index;
String temp = null;
int length = a.length;
for (index = 0; index < length; index++) {
if (a[index].endsWith(ending)) {
temp = a[index];
break;
}
}
if (temp != null) {
int tempLength = temp.length();
for (index = 0; index < b.length; index++) {
b[index] = temp.substring(0, tempLength);
}
}
}
阅读全文