1

我在让我的 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 数组?在此先感谢您的帮助。

4

1 回答 1

2

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

 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
        }
于 2013-01-30T01:36:46.547 回答