1

ここに私のコードのスニペットがあります:

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

4 に答える 4

4

null で呼び出すと、 を返すときにNPEがスローされます。while ループは次のようになります。br.readLine()nulllength()

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

今、あなたの whilebufferedReaderに null を返しても終了します。readLine()

于 2013-01-28T16:17:06.590 に答える
1

おそらく、あなたは変わりたいと思っています

while(name != null)

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

このようにして、 la read from をチェックしていて、brneverでnullあることを確認できます。namenull

于 2013-01-28T16:20:14.017 に答える
0

これを行う適切な方法は次のとおりです。

String name = null;

while((name = br.readLine()) != null) {
    ...
}
于 2013-01-28T16:18:36.463 に答える
0
name = br.readLine();

null を返す可能性があります。それはあなたが期待するものですか?docから、次を返します。

行終了文字を含まない、行の内容を含む文字列、またはストリームの末尾に到達した場合は null

そのため、入力の最後に達した可能性があります。

于 2013-01-28T16:16:53.473 に答える