有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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是我剪切的代码的一部分,所以有字符串变量。请帮忙回答。谢谢


共 (4) 个答案

  1. # 1 楼答案

    br.readLine()返回null时,当您在null上调用length()时,它抛出NPE。 您的while循环应该如下所示:

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

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

  2. # 2 楼答案

    也许,你想要改变

    while(name != null)
    

    while((name = br.readline()) != null)
    

    通过这种方式,您可以检查从br读取的la与null之间的关系,并且可以确保name永远不会null

  3. # 3 楼答案

    name = br.readLine();
    

    很可能返回null。这就是你所期待的吗?从the doc返回:

    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

    所以你可能已经完成了你的输入

  4. # 4 楼答案

    正确的方法是:

    String name = null;
    
    while((name = br.readLine()) != null) {
        ...
    }