Java扫描程序类没有此类元素异常错误

时间:2019-09-20 10:19:42

标签: java java.util.scanner

我有一个带有静态方法的类Test来接受输入。

 class Test {
        public static Student readStudent() throws IOException {
            Scanner s = new Scanner(System.in);
            System.out.println("Enter first name of student");
            String fname = s.nextLine();
            System.out.println("Enter middle name of student");
            String mname = s.nextLine();
            System.out.println("Enter last name of student");
            String lname = s.nextLine();
            System.out.println("Enter name format(1 for ',' and 2 for ';') ");
            int num = s.nextInt();
            System.out.println("Enter age of student");
            int age = s.nextInt();

            s.close();

            return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
                    mname, lname)), age);

        }
    }

我能够为一个学生接受输入,但是一旦将其输入for循环中,就会出现java.util.NoSuchElementException: No line found错误。

这是我的循环

for (int i = 0; i < 10; i++) {
            Student s = Test.readStudent();
        }

为什么会出现此错误?谢谢。

1 个答案:

答案 0 :(得分:2)

s.close();关闭当前的Scanner对象,同时关闭所有基础流,在这种情况下,该流为System.in。关闭标准输入流后,您将无法再打开它。

因此,总的来说,最好在确定不再需要它后再关闭扫描仪并按以下方式重新构建代码:

Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
    Student s = Test.readStudent(sc);
    // do something with your student object here
}
sc.close();

并将您的方法更改为

public static Student readStudent(Scanner s) throws IOException {
    Scanner s = new Scanner(System.in);
    System.out.println("Enter first name of student");
    String fname = s.nextLine();
    System.out.println("Enter middle name of student");
    String mname = s.nextLine();
    System.out.println("Enter last name of student");
    String lname = s.nextLine();
    System.out.println("Enter name format(1 for ',' and 2 for ';') ");
    int num = s.nextInt();
    s.nextLine(); // Need to consume new line
    System.out.println("Enter age of student");
    int age = s.nextInt();
    s.nextLine(); // Need to consume new line

    // no closing here

    return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
                mname, lname)), age);
}