首页 > 解决方案 > 用于课堂程序的多个扫描仪,我不知道如何拥有多个

问题描述

我需要在 Java 程序中为我的 CS1400 课程制作四个扫描仪。有人告诉我让每个扫描仪有一个不同的变量名,但这样做只会导致程序崩溃,并显示错误读取“线程“主”java.util.NoSuchElementException 中的异常”。我不确定我做错了什么,这可能相当简单。我的 Java 和 IntelliJ(课程需要)全部更新。

第一个扫描仪的缩写:

System.out.println();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = keyboard.nextInt();
System.out.println("You entered: " + number);
keyboard.close();

第二个扫描仪的缩短代码:

System.out.println();
Scanner scanObj = new Scanner(System.in);
System.out.println("Enter a number: ");
int id = scanObj.nextInt();
System.out.println("You entered " + id);
scanObj.close();

免责声明:我知道两个扫描仪都在做同样的事情,这只是我为我的问题输入的示例代码。

标签: java

解决方案


如果您使用的是控制台应用程序,建议您只使用一个扫描仪。当您有多个扫描仪时,由于某些流/扫描仪未正确关闭,您可能会遇到已经遇到的错误。

参考这篇文章:Scanner NoSuchElementException


推荐阅读