2015-07-02 51 views
-5

我想打一个字符串数组阵列中的Java空指针异常的字符串

我没有为它

因为它必须被初始化固定大小的,我用空intialize它..它给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; 
} 
+1

此代码甚至不会编译。你想在这里实现什么。 –

+1

java中的数组总是固定的大小 - 如果您需要可变大小,请使用'List' –

+0

您应该使用List而不是数组来避免迭代期间的NullPointerExceptions。 – sinclair

回答

0

如果您不知道大小,列表总是更好。

为了避免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); 

当你这样做,你比较两个值,它会返回true或false。您可能希望将值添加到列表中,在这种情况下,您必须这样做:

matchedList.add(result);