开发者

Scanner.nextLine() not returning null?

I'm a student and I decided to try out some of the problem sets at UVa Online Judge to help improve my skill. I ran into a brick wall on the first problem. After fighting compiler errors (I finally found some vague guidelines for submitting Java code in their forums), I've now graduated to "Wrong Answer" status.

To get to the point -- if I don't surround this while loop with a try/catch, it generates a NumberFormatException at runtime on input string "" on the call to Integer.parseInt(). That makes sense, except if input is "" then it is null and should not enter the loop.

I've tried getting rid of split(" ") and use a StringTokenizer, but that generates开发者_高级运维 an wrong index exception.

The program works fine until I end input by hitting Enter. That's when the error generates. If I surround the loop with a try/catch, there's no errors, but the console seems to throw in an additional line break, and I believe that's the source of my "Wrong Answer" status.

What am I doing wrong?

public static void main(String[] args){
     Scanner kb = new Scanner(System.in);
     String input;
     String[] temp;
     int i, j;

     while( (input = kb.nextLine()) != null ){
        temp = input.split(" ");
        i = Integer.parseInt(temp[0]);
        j = Integer.parseInt(temp[1]);
        solve(i, j);
     }
}


It is unclear why you're expecting kb.nextLine() to return null when an empty line is entered. You should compare against "" instead of null.

You should also check kb.hasNextLine() before calling kb.nextLine().

public static void main(String[] args){
     Scanner kb = new Scanner(System.in);
     String[] temp;
     int i, j;

     while (kb.hasNextLine()) {
        String input = kb.nextLine();
        if (input.equals("")) break;
        temp = input.split(" ");
        i = Integer.parseInt(temp[0]);
        j = Integer.parseInt(temp[1]);
        solve(i, j);
     }
}


There is a next line so it won't return null its just that the line is empty and thus "".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜