【问题标题】:Array of strings in Java NULL pointer exceptionJava NULL 指针异常中的字符串数组
【发布时间】:2015-07-02 07:55:06
【问题描述】:

我想做一个字符串数组

我没有固定尺寸

因为它必须被初始化,所以我用null初始化它。它给java空指针异常???

在我的代码的另一部分,我在数组上循环以打印其内容.. 那么如何在没有固定大小的情况下克服这个错误

   public static String[] Suggest(String query, File file) throws FileNotFoundException
{
    Scanner sc2 = new Scanner(file);
    LongestCommonSubsequence obj = new LongestCommonSubsequence();
    String result=null;
    String matchedList[]=null;
    int k=0;

    while (sc2.hasNextLine()) 
    {
        Scanner s2 = new Scanner(sc2.nextLine());
        while (s2.hasNext()) 
            {
            String s = s2.next();
            //System.out.println(s);
            result = obj.lcs(query, s);

                if(!result.equals("no match"))
                {matchedList[k].equals(result); k++;}

            }
        return matchedList;
    }
    return matchedList;
}

【问题讨论】:

  • 这段代码甚至无法编译。你想在这里实现什么。
  • Java 中的数组始终是固定大小的 - 如果您需要可变大小,请使用 List
  • 您应该使用 List 而不是数组,以避免在迭代过程中出现 NullPointerExceptions。
  • @TimBiegeleisen 我正在做的事情是:
  • @sinclair 初始化为 null 的列表变量仍会引发 NPE。

标签: java arrays


【解决方案1】:

如果你不知道大小,List 总是更好。

为了避免 NPE,你必须像这样初始化你的列表:

List<String> matchedList = new ArrayList<String>(); 

ArrayList 是一个例子,你可以使用你需要的所有列表之王。

为了得到你的元素而不是matchedList[index],你将拥有这个:

macthedList.get(index);

所以我们的代码会是这样的:

public static String[] Suggest(String query, File file) throws FileNotFoundException
{
...
List<String> matchedList= new ArrayList<String>();
...

while (sc2.hasNextLine()) 
{
    Scanner s2 = new Scanner(sc2.nextLine());
    while (s2.hasNext()) 
    {
        ...
        if(!result.equals("no match")){
          //This line is strange. See explanation below
          matchedList.get(k).equals(result);
          k++;
         }
    }
    return matchedList;
}
return matchedList;
}

你的代码有些奇怪:

matchedList.get(k).equals(result);

当你这样做时,你比较两个值,它会返回真或假。您可能想在列表中添加值,在这种情况下,您必须这样做:

matchedList.add(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    相关资源
    最近更新 更多