【问题标题】:Java Scanner No Line Found, Not waiting for user inputJava Scanner No Line Found,不等待用户输入
【发布时间】:2013-01-13 18:01:06
【问题描述】:

我在让我的 Scanner 对象读取用户输入时遇到问题。我希望扫描仪读取用户输入并将输入保存到字节数组中。

如果我使用以下代码:

import java.util.Scanner;

public class ExamTaker {
    public static void main(String[] args) {
        // Variable Declaration
        char[] studentTest = new char[20];

        // Input Setup
        Scanner keyboard = new Scanner(System.in);

        // Take the test
        for (int i = 0; i < studentTest.length; i++) {
            System.out.print("\nAnswer " + (i+1) + " : ");
            studentTest[i] = keyboard.nextLine().charAt(0); // The troubled line
        }
    }
}

我得到如下异常错误:

Answer 1 : Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at ExamTaker.main(ExamTaker.java:14)

通过 Stack Overflow 和 Google 进行研究后,我接受了将我的问题行放入 try-catch 的建议,如下所示:

// Take the test
        for (int i = 0; i < studentTest.length; i++) {
            System.out.print("\nAnswer " + (i+1) + " : ");
            try {
                studentTest[i] = keyboard.nextLine().charAt(0);
            }
            catch (Exception e) {
                System.out.print("Exception found");
            }
        }

但是,这仍然不会产生所需的输出,因为我认为我使用 nextLine() 方法的方式存在问题。它只是在每个编号的答案前面抛出“发现异常”文字。

我还尝试将 for 循环更改为 do-while 循环,并在没有到达行尾的情况下折腾一个 keyboard.getChar(),但无济于事。

在这种情况下,如何让用户输入一个字符串,在该字符串中我取第一个字符并将其分配给我的 char 数组?提前感谢您的帮助。

【问题讨论】:

    标签: java loops input char


    【解决方案1】:

    Scanner#nextLine() throw NoSuchElementException when no line is found,你应该在调用 nextLine() 之前调用 Scanner#hasNextLine() 以确保下一行存在于扫描仪中。

     for (int i = 0; i < studentTest.length; i++) {
                System.out.print("\nAnswer " + (i+1) + " : ");
                if(keyboard.hasNextLine()){
                    studentTest[i] = keyboard.nextLine().charAt(0); // The troubled line
                 }
            }
    

    另外,我发现您只想从扫描仪获取用户输入,为什么不直接使用 Scanner#next()

    for (int i = 0; i < studentTest.length; i++) {
                System.out.print("\nAnswer " + (i+1) + " : ");
                studentTest[i] = keyboard.next().charAt(0); // The troubled line
            }
    

    【讨论】:

    • 感谢您的回复!在建议的条件中包含有问题的行可以避免引发异常,但不允许用户输入。我的假设是,由于不存在这样的行,它没有通过条件语句。此外,使用 'next()' 会得到与以前相同的 'NoSuchElementException'。
    猜你喜欢
    • 2014-06-20
    • 1970-01-01
    • 2021-01-19
    • 2021-03-05
    • 2013-05-25
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多