Java.NullPointerException 为空

标签 java null nullpointerexception

<分区>

以下是我的代码片段:

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 有字符串变量 因为它是我删除的代码的一部分。请帮忙解答。谢谢。

最佳答案

br.readLine() 返回 null 时,它抛出 NPE,因为你调用 length()无效的。 你的 while 循环应该像下面这样:

while((name= br.readLine())!=null){
        namelenx = name.length();

现在,即使 bufferedReaderreadLine() 上返回 null,您的 while 也会终止。

关于Java.NullPointerException 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14566291/

相关文章:

java - 为什么这个循环排序实现有一个错误?

MySQL:获取日期为 NULL 的行,或者如果存在则获取具有设置日期的行

c++ - 像测试指针一样测试 C++ 对象的有效性

java - 缓冲读取器的标记化问题

java - 如何使用 lambda 表达式将条件发送到方法以便尚未对其进行评估?

java - 父类中的构造函数不能被应用

java - GWTTestCase - 未找到测试

kotlin - 如果构造函数不能返回 null,为什么我需要在初始化后进行类型检查?

java - 部署在 mochahost 共享服务器上时出现 NullPointerException 获取连接

android - 通过广播 Intent 传递 ArrayList