java - 扫描仪抛出 NoSuchElementException

标签 java int java.util.scanner nosuchelementexception

我正在尝试创建一个简单的小程序,它将要求一个正整数,并且在收到用户的正整数之前不会崩溃或关闭。但是,当我的程序多次调用包含 Scanner 的方法时,它会不断崩溃,并报告错误 NoSuchElementException。我将使用这个程序的基础知识来帮助我正在做的其他事情。这是我当前的代码;

import java.util.InputMismatchException;
import java.util.Scanner;

public class test2 {

/**
 * Test ways to avoid crashes when entering integers
 */
public static void main(String[] args) {
    int num = testnum();
    System.out.println("Thanks for the " + num + ".");
}

public static int testnum() {
    int x = 0;
    System.out.println("Please enter a positivie integer;");
    x = getnum();
    while (x <= 0) {
        System.out.println("That was not a positive integer, please enter a positive integer;");
        x = getnum();
    }
    return x;
}

public static int getnum() {
    Scanner scan = new Scanner(System.in);
    int testint;
    try {
        testint = scan.nextInt();
    } catch (InputMismatchException e) {
        scan.close();
        return 0;
    }
    scan.close();
    return testint;
}
}

任何帮助将不胜感激,谢谢:)

最佳答案

不要在 getnum() 方法中关闭扫描仪。

public static int getnum() {
    Scanner scan = new Scanner(System.in);
    int testint;
    try {
        testint = scan.nextInt();
    } catch (InputMismatchException e) {
        scan.close();
        return 0;
    }
//    scan.close();
    return testint;
}

关于java - 扫描仪抛出 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17873835/

相关文章:

java - 如何使 4 个微调器相互依赖

java - 将一个字符追加到 JTextArea

C char 在编译时显示为 int

java - 扫描带有空格和逗号的行

java - 如何让程序在 for 循环内等待用户输入?

java - Springboot @Retryable 包含多个异常

java - 如何在运行时更改外部类日志记录级别后刷新 log4j

java - 一起使用 String 和 int 时的 System.out.println 行为

java - 如何在Java中将RGB颜色转换为十六进制

java - 必需的: variable Found:value Error Java Text-Based Calculator