Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFo
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at com.Eshyee.Prog.Progress.main(Progress.java:16)
package com.Eshyee.Prog;
import java.util.Scanner;
public class Progress {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.close();
Student[] a=new Student[n];
Scanner up =new Scanner(System.in);
for(int i=0;i<n;i++) {
a[i]=new Student();
a[i].name=up.next();
a[i].id=up.next();
a[i].grade=up.nextInt();
}
up.close();
for(int i=0;i<n;i++) {
System.out.println(a[i].name);
System.out.println(a[i].id);
System.out.println(a[i].grade);
}
}
}
class Student{
String name;
String id ;
int grade;
} 展开
import java.util.Scanner;
public class Progress {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//这里只能输入数字
int n = in.nextInt();
Student[] a = new Student[n];
Scanner up = new Scanner(System.in);
for (int i = 0; i < n; i++) {
a[i] = new Student();
a[i].name = up.next();
a[i].id = up.next();
a[i].grade = up.nextInt();
}
up.close();
in.close();
for (int i = 0; i < n; i++) {
System.out.println(a[i].name);
System.out.println(a[i].id);
System.out.println(a[i].grade);
}
}
}
class Student {
String name;
String id;
int grade;
}
这个是正确的代码,原因出在第一个scanner类你将他close()了,当调用close()后,System.in这个流将会关闭,所以也就影响到了第二个scanner了,导致不能接受数据,从而引发java.util.NoSuchElementException.