我有一个一直在尝试运行的代码。它给了我一个NoSuchElementException。
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
System.out.println("Insert Names:");
List<String> names = getNames();
System.out.println("Insert Marks:");
List<Integer> marks = getMarks();
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
int mark = marks.get(i);
System.out.println( name + " - " + mark);
}
}
private static List<String> getNames() {
List<String> names= new ArrayList<>();
Scanner scanner = new Scanner( System.in );
for ( int i = 0 ; i < 3; i++){
names.add(scanner.nextLine());
}
scanner.close();
return names;
}
private static List<Integer> getMarks() {
List<Integer> names= new ArrayList<>();
Scanner scanner = new Scanner( System.in );
for ( int i = 0 ; i < 3; i++){
names.add(scanner.nextInt());
}
scanner.close();
return names;
}
}
在我读完名字后就会发生此错误。为什么会发生错误。
答案 0 :(得分:0)
您的扫描仪将System.in
作为输入流。调用scanner.close()时,它将同时关闭扫描器和输入流。关闭的流无法重新打开。
如果要关闭扫描仪,可以在主要方法中创建一个扫描仪,稍后再关闭。可以将它作为参数传递给其他两种方法。
您可以这样调用代码
public static void main(String[] args) {
Scanner scanner = new Scanner( System.in );
System.out.println("Insert Names:");
List<String> names = getNames( scanner );
System.out.println("Insert Marks:");
List<Integer> marks = getMarks( scanner );
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
int mark = marks.get(i);
System.out.println( name + " - " + mark);
}
scanner.close();
}
private static List<String> getNames(Scanner scanner) {
List<String> names= new ArrayList<>();
for ( int i = 0 ; i < 3; i++){
names.add(scanner.nextLine());
}
return names;
}
private static List<Integer> getMarks( Scanner scanner) {
List<Integer> names= new ArrayList<>();
for ( int i = 0 ; i < 3; i++){
names.add(scanner.nextInt());
}
return names;
}