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 :)