我正在codingbat.com/java中编码,遇到了一个我不明白的错误。我有两个字符串数组,并想比较它们。如果我只使用数组,所有的工作都很好(但结果不对)。为了得到正确的结果,我编写了一个助手函数,它消除了数组的所有重复。我测试了helper函数,它返回缩短的重复数组。
我可以使用_a[i]等检索新数组中的值,并且不会出现错误,但是如果我使用_a[0].equals(_b[0]) or _a[0].compareTo(_b[0]),就会得到一个NullPointerException (_a[0] == _b[0] works fine...)。
如果我只使用原始数组a,b代码运行时没有问题。我不明白为什么我在那里有一个NullpointerException。
谢谢你的帮助!
代码:
public int commonTwo(String[] a, String[] b) {
String[] _a = killDuplicate(a);
String[] _b = killDuplicate(b);
int ai=0, bi=0,count=0;
for (int i = 0; ai < _a.length & bi < _b.length; i++){
if ( _a[ai].compareTo(_b[bi]) > 0) { //NullPointerException here, but not if I use a,b
bi++;
} else if ( _a[ai].compareTo(_b[bi]) < 0){ //NullPointerException here, but not if I use a,b
ai++;
} else {
count++;
ai++;
bi++;
}
}
return count;
}帮助函数:
public String[] killDuplicate(String[] a){
String temp = "";
int counter = 0, counter2 = 0;
for (int i = 0; i < a.length; i++){
if (! a[i].equals(temp)){
temp = a[i];
} else {
a[i] = "";
counter++;
}
}
String[] result = new String[a.length - counter];
for (int i = 0; counter2 < counter; i++){
if (a[i].equals("")) {
counter2++;
}
} else {
result[i-counter2] = a[i];
}
return result;
}发布于 2013-08-07 10:52:58
我猜您假设您的字符串数组是排序的,否则您的killDuplicate方法根本就没有意义。
代码的问题是,在killDuplicate方法中的第二个killDuplicate循环中,您使用条件counter2 < counter迭代,条件counter2 < counter说,迭代直到所有找到的重复项都被传递。因此,当您找到最后一个副本时,就退出,而不填充数组的其余部分。尝试使用示例:new String[]{"A", "A", "B", "C"},您将得到[A, null, null]。
有很多东西可以改进,但下面是最简单的代码修改。(我只更改了第二个for循环)公共String[] killDuplicate(String[] a) {
String temp = "";
int counter = 0, counter2 = 0;
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(temp))
temp = a[i];
else {
a[i] = "";
counter++;
}
}
String[] result = new String[a.length - counter];
for (int i = 0; i < a.length; i++) {
if (a[i].equals("")) continue;
result[counter2] = a[i];
counter2++;
}
return result;
}https://stackoverflow.com/questions/18101147
复制相似问题