nextInt()始终抛出NoSuchElementException,hasNext相关判断仍无效
解决Scanner调用nextInt()抛出NoSuchElementException的问题
嘿,我一眼就看出问题所在了——你不小心重复关闭了标准输入流System.in,这才导致了后续所有读取操作都失败!
问题根源
在你的main方法里,你创建了一个Scanner实例后直接调用了scan.close(),这会彻底关闭底层的System.in输入流。之后当你在readIntegers方法里新建另一个Scanner时,它面对的是已经关闭的流,根本无法读取任何数据。这就是为什么你用hasNextInt或hasNextLine判断时始终返回false,调用nextInt()自然就抛出NoSuchElementException了。
解决方案
核心原则是:整个程序只使用一个针对System.in的Scanner实例,并且只在所有读取操作完成后统一关闭它。具体可以这么改:
- 将
Scanner作为参数传递给readIntegers方法,避免重复创建实例 - 移除
main方法中提前关闭Scanner的代码,只在程序结束时关闭 - 可以添加输入验证逻辑,确保用户输入的是有效整数(可选,但能提升程序健壮性)
修改后的完整代码
import java.util.Scanner; public class MinimumElement { // 接收外部传入的Scanner,共享同一个输入流 public void readIntegers(int userCount, Scanner scan) { int[] intArray = new int[userCount]; for (int i = 0; i < userCount; i++) { System.out.println("Please input number " + (i + 1) + ":"); // 验证输入是否为整数,避免无效输入导致异常 while (!scan.hasNextInt()) { System.out.println("Oops, that's not an integer! Please try again:"); scan.nextLine(); // 跳过当前无效的输入行 } int number = scan.nextInt(); intArray[i] = number; } // 这里不要关闭Scanner,交给上层main方法处理 } public static void main(String[] Args) { Scanner scan = new Scanner(System.in); System.out.println("Please enter the number of elements required for array:"); // 先验证用户输入的元素数量是否为有效整数 while (!scan.hasNextInt()) { System.out.println("Invalid input! Please enter a positive integer:"); scan.nextLine(); } int userInput = scan.nextInt(); scan.nextLine(); // 读取掉换行符,避免后续读取时出现问题 MinimumElement min = new MinimumElement(); min.readIntegers(userInput, scan); // 所有读取操作完成后,再关闭Scanner scan.close(); } }
额外说明
- 永远不要在还需要读取输入的时候关闭
Scanner(尤其是针对System.in的),因为关闭Scanner会连带关闭底层的System.in流,且这个流是无法重新打开的。 - 多个
Scanner实例共享同一个System.in流时,只要其中一个被关闭,其他所有实例都会失效,所以尽量全程只用一个Scanner。
内容的提问来源于stack exchange,提问作者Abhishek Singh
相关产品推荐
相关产品推荐

