简体   繁体   English

Scanner.nextLine()不返回null?

[英]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. 我是一名学生,所以我决定尝试在UVa Online Judge中解决一些问题,以帮助提高我的技能。 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. 解决了编译器错误之后(我终于在他们的论坛中找到了一些有关提交Java代码的模糊指导),现在我已经升为“错误答案”状态。

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() . 准确地说-如果我不使用try / catch包围while循环,则会在运行时在Integer.parseInt()的调用中在输入字符串""上生成NumberFormatException That makes sense, except if input is "" then it is null and should not enter the loop. 这是有道理的,除非输入为""否则它为null且不应进入循环。

I've tried getting rid of split(" ") and use a StringTokenizer , but that generates an wrong index exception. 我尝试摆脱split(" ")并使用StringTokenizer ,但这会生成错误的索引异常。

The program works fine until I end input by hitting Enter. 该程序运行良好,直到我按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. 如果我用try / catch包围循环,则没有错误,但是控制台似乎抛出了额外的换行符,并且我相信这是我的“错误答案”状态的来源。

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. 目前尚不清楚为什么期望在输入空行时kb.nextLine()返回null You should compare against "" instead of null . 您应该与""进行比较,而不是null

You should also check kb.hasNextLine() before calling kb.nextLine() . 您也应该检查kb.hasNextLine()调用之前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);
     }
}

还有下一行,因此它不会返回null只是该行为空,因此为""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM