0

I'm coding trough codingbat.com/java and ran into an error i don't understand. I got two String arrays and want to compare them. If I just use the arrays all works fine (but the result is not right). To get the right result I programmed a helper function which eliminates all duplicates of an array. I tested the helper function, it returns the array shortened of the duplicates.

I can retrieve the values in the new Arrays with _a[i] etc., and don't get errors, but if i use _a[0].equals(_b[0]) or _a[0].compareTo(_b[0]) I get a NullPointerException (_a[0] == _b[0] works fine...).

If I just use the original arrays a,b the code runs without problems. I don't comprehend why i get a NullpointerException there.

Thanks for any help!

Code:

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;
}

Helper Function:

 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;
 }
4

1 回答 1

0

我猜你假设你的字符串数组是排序的,否则你的killDuplicate方法根本没有意义。

您的代码的问题在于,for在方法的第二个循环中,killDuplicate您使用条件进行迭代,counter2 < counter该条件表示迭代直到所有找到的重复项都通过。因此,当您找到最后一个副本时,您将退出而不填充数组的其余部分。举个例子:new String[]{"A", "A", "B", "C"}你会得到[A, null, null].

有很多事情可以改进,但最简单的修改如下代码。(我只改变了第二个for循环) 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; i < a.length; i++) {
        if (a[i].equals("")) continue;
        result[counter2] = a[i];
        counter2++;
    }

    return result;
}
于 2013-08-07T10:52:58.757 回答