我正在研究 Java 类,我正在尝试创建一个代码,用户可以在其中输入他们想要创建的对象(在本例中为“立方体”)的数量。
在我的主类中,我编写了这段代码
System.out.println("Enter the amount of objects you want to create");
Scanner objNumInput = new Scanner(System.in);
int objNum = objNumInput.nextInt();
objNumInput.close();
Cube cubes[] = new Cube[objNum];
for (int i = 0; i < objNum; i++){
String cubeName = Cube.inputName();
double cubeLength = Cube.inputLength();
cubes[i] = new Cube(cubeName, cubeLength);
}
在我的 Cube 类中,我在这里:
public static String inputName(){
String cubeName;
Scanner input = new Scanner(System.in);
System.out.println("Enter the name: ");
cubeName = input.nextLine();
return cubeName;
}
public static double inputLength(){
double cubeLength;
Scanner input = new Scanner(System.in);
System.out.println("Enter the length: ");
cubeLength = input.nextDouble();
return cubeLength;
}
当我运行它时,我可以输入我想要创建的“立方体”的数量。然后,一直抛异常
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Cube.inputName(Cube.java:40)
at Main.main(Main.java:88)
怎么了?
最佳答案
不要关闭你的Scanner
,它也会关闭System.in
。
When a Scanner is closed, it will close its input source if the source implements the Closeable interface
据我了解(如果我错了请纠正我)您关闭 objNumInput
的原因是您想以两种不同的方法使用它。
我建议您将 Scanner
作为输入参数传递到您的方法 inputName
和 inputLength
中。然后您就可以重复使用同一个扫描仪,而无需在两者之间关闭它。
public static String inputName(Scanner scanner){
String cubeName;
System.out.println("Enter the name: ");
cubeName = scanner.nextLine();
return cubeName;
}
public static double inputLength(Scanner scanner){
double cubeLength;
System.out.println("Enter the length: ");
cubeLength = scanner.nextDouble();
return cubeLength;
}
...
System.out.println("Enter the amount of objects you want to create");
Scanner objNumInput = new Scanner(System.in);
int objNum = objNumInput.nextInt();
//objNumInput.close(); <-- Do not close the scanner
Cube cubes[] = new Cube[objNum];
for (int i = 0; i < objNum; i++){
String cubeName = Cube.inputName(objNumInput);
double cubeLength = Cube.inputLength(objNumInput);
cubes[i] = new Cube(cubeName, cubeLength);
}
关于java - 如何让 java 在将输入分配给变量之前等待输入以避免 java.util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53333764/