【发布时间】: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。