Java Scanner No Line Found,不等待用户输入

时间:2013-01-30 01:32:33

标签: java loops input char

我在让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进行研究后,我采取了建议,将我的烦恼线放入试用捕获中,如下所示:

// 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()方法的问题,这仍然不会产生所需的输出。它只是在每个编号的答案前面抛出“Exception found”字面。

我也尝试将for循环更改为do-while循环,然后抛入keyboard.getChar(),以防它没有到达行尾,但无效。

如何让用户输入一个字符串,在该字符串中我将第一个字符分配给此实例中的char数组?在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

Scanner#nextLine() 抛出NoSuchElementException当找不到行时,您应该在调用{{1}之前调用 Scanner#hasNextLine() 确保扫描仪中存在下一行。

nextLine()

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

 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
             }
        }
相关问题