Scanner throwing NoSuchElementException

≡放荡痞女 提交于 2019-12-08 03:38:03

问题


I am trying to create a simple small program that will ask for a positive int and won't crash or close until it has received a positive int from the user. However my program keeps crashing, and reporting the error NoSuchElementException, when it calls the method with Scanner in it more than once. I will be using the fundamentals of this program to help some other things I am working on. Here is my current code;

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;
}
}

Any help would be greatly appreciated, thank you :)


回答1:


Do not close the scanner at getnum() method.

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;
}



回答2:


Try out this class, comments in the code explain it all.

import java.util.Scanner;

public class GetPositiveInteger {

    private static Scanner scan = new Scanner(System.in); //scanner variable accessible by the entire class

    /*
     * main method, starting point
     */
    public static void main(String[] args) { 
        int num = 0; //create an integer
        while(num <= 0) //while the integer is less than or equal to 0
            num = getPostiveNumber(); //get a new integer
        System.out.println("Thanks for the number, " + num); //print it out
    }
    public static int getPostiveNumber() { //method to get a new integer
        System.out.print("Enter a postive number: "); //prompt
        try {
            return scan.nextInt(); //get the integer
        } catch (Exception err) {
            return 0; //if it isn't an integer, try again
        }
    }
}


来源:https://stackoverflow.com/questions/17873835/scanner-throwing-nosuchelementexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!