【发布时间】:2016-07-01 11:49:59
【问题描述】:
我正在编写一个从文件读取的 java 程序,我需要它在文件末尾停止,我记得过去使用“While(line != null)”来获取文本中的每一行,但是,它现在不适合我。我的方法是这样的:
int contator = 0;
String line2 = "";
while (line2 != null) {
line2 = reader2.readLine();
fi[contator]=line2;
for(int i =0;i<ret.length;i++){
System.out.println("line2 : "+line2+"ret : "+ret[i]);
if(line2.toLowerCase().contains(ret[i])){
fi[contator] = line2;
etiqueta[contator]=etiqueta[contator]+" reti";
}
}contator ++;
}
它正在工作,我看到打印正确,但是当它必须结束时,用 null 打印最后一行,并以“java.lang.NullPointerException”退出;打印
line2 : Number of words ret : 361.
line2 : Something here ret : 369.
line2 : other things ret : 379.23
line2 : nullret : 250.5//this is the problem, after this it throws exception
我尝试了其他方法,例如:
while (line2 != "null" )
while (line2.length()>0)
while (!line2.isEmpty)
没有任何效果,我在 Eclipse IDE Mars.2 上;任何的想法? 提前致谢。
【问题讨论】:
-
while (line2 != "null" )请重新考虑这种方法并考虑它的真正作用。特别想"null"的含义。 -
是的,我知道这没有任何意义,我在这里对字符串进行某种“强制转换”,我有点迷失了,可能要花很多时间编程。
-
不,你没有在这里转换任何东西,因为
line2已经是一个字符串,但是你正在检查变量line2是否引用了与字符串文字 @987654328 相同的字符串对象@。而"null"与null非常不同。但是您已经知道为什么您原来的while (line2 != null)不能正常工作,所以这一切都很好:)。
标签: java arrays nullpointerexception bufferedreader