JAVANullPointerException null
以下是我的代码片段:
class Lines{
int nameMax() throws IOException{
// initialize variables
// These will be the largest number of characters in name
int namelen = 0;
//These will be the current word lenght.
int namelenx = 0;
...
while(name != null){
name = br.readLine();
namelenx = name.length();
...
if(namelenx > namelen) namelen = namelenx;
}
float nameleny = namelen/2; //Divides by 2 to find midpoint
namelen = Math.round(nameleny); //Value is rounded
return namelen;
}
}
我使用的是BlueJ,每当我尝试运行它时,它都会在标题和突出显示namelenx = name.length();
中给出错误。因为name
是我剪切的代码的一部分,所以有字符串变量。请帮忙回答。谢谢
# 1 楼答案
当
br.readLine()
返回null
时,当您在null上调用length()
时,它抛出NPE。 您的while循环应该如下所示:现在,即使
bufferedReader
在readLine()
上返回null,您的while也会终止# 2 楼答案
也许,你想要改变
到
通过这种方式,您可以检查从
br
读取的la与null
之间的关系,并且可以确保name
永远不会null
# 3 楼答案
很可能返回null。这就是你所期待的吗?从the doc返回:
所以你可能已经完成了你的输入
# 4 楼答案
正确的方法是: