muka90 muka90 - 19 days ago 6
Java Question

JAVA: Workaround for nextline() after nextInt() doesn't work

I want to use a class inputs with the methods inputInt & inputString so that its cleaner code when i need to parse a input.

At first I ask for an Int to choose menue. Then, after a syso, I want to get a String from the user. But after the menue got chosen correctly I immediatly get the catch clause from InputString.

I've already read all the questions before and the solutions should work for me too I think but it doesn't.
Thanks in advance!

public class Inputs{

public static int inputInt(){
try {
Scanner scanner = new Scanner(System.in);
int input = Integer.parseInt(scanner.nextLine());
scanner.close();

return input;
} catch (NumberFormatException e) {
System.out.println("INT ONLY! "+e);
}
return 0;
}
public static String inputString(){
try {
Scanner scanner1 = new Scanner(System.in);
String inputString=scanner1.nextLine();
scanner1.close();

return inputString;
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("String Only!");
}
return null;
}


calling in:

public static void doSomething(){

System.out.println("enter String: ");
x= Inputs.inputString();

Answer

At first I ask for an Int to choose menue. Then, after a syso, I want to get a String from the user. But after the menue got chosen correctly I immediatly get the catch clause from InputString.

Probably you get this:

java.lang.IllegalStateException: Scanner closed

When you close a Scanner, it closes the underlying input stream. Your inputInt and inputString methods both create a new Scanner from System.in, and close the scanner when they are done. So after the first use of any of these methods, System.in will be closed, and you cannot read from it again. Hence the exception.

The solution is to create a single Scanner instance, and reuse it with these two methods. For example something like this:

public static int inputInt(Scanner scanner) {
    try {
        return Integer.parseInt(scanner.nextLine());
    } catch (NumberFormatException e) {
        System.out.println("INT ONLY! " + e);
    }
    return 0;
}

public static String inputString(Scanner scanner) {
    try {
        return scanner.nextLine();
    } catch (Exception e) {
        // System.out.println("String Only!");
    }
    return null;
}

I commented out the System.out.println("String Only!"); in inputString, because it doesn't make sense there. An exception thrown there will not mean that the input was not a string, so such message would be inaccurate and confusing.