1 回答
TA贡献1719条经验 获得超6个赞
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);
}
添加回答
举报