首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当比较两个不同字符串数组的两个字符串时,Exception:java.lang.NullPointerException

当比较两个不同字符串数组的两个字符串时,Exception:java.lang.NullPointerException
EN

Stack Overflow用户
提问于 2013-08-07 10:34:59
回答 1查看 1K关注 0票数 0

我正在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。

谢谢你的帮助!

代码:

代码语言:javascript
复制
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;
}

帮助函数:

代码语言:javascript
复制
 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;
 }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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) {

代码语言:javascript
复制
    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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18101147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档