1

I'm trying to only allow an integer input and stop my programm from breaking when something else is entered. Somehow my code creates an endless loop and doesn't let me enter a new input.

    private static int x;

    public static void main(String[] args) {
        testInput();
    }

    public static void testInput(){
        while (true){
            System.out.println("Please enter Integer:");
            try{
                setX(scanner.nextInt());
                break;
            }catch (InputMismatchException i){
                System.out.println("Please use Integer");
            }
        }
    }

    public static void setX(int integer){
        x = integer;
    }
}

Creates endless loop which says: Please enter Integer: , Please use Integer instead of letting me make new input.

2
  • 3
    I'm sure this is a duplicate, but basically scanner.nextInt() doesn't consume the token if it's not an integer. I'd personally be tempted to avoid Scanner entirely, and just read lines from System.in instead. I've seen a lot of questions about Scanner that basically show it's a hard to use API. Commented Jun 20, 2019 at 14:11
  • Relevant but not a dup: Scanner is skipping nextLine() after using next() or nextFoo()? Commented Jun 20, 2019 at 14:13

1 Answer 1

3

You're on the right track with a while loop, basically, you just need to use Scanner.next() when the user enters something other than an integer:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String prompt = "Please enter an integer: ";
        int userInteger = getIntegerInput(prompt, scanner);
        System.out.printf("You entered: %d%n", userInteger);
    }

    private static int getIntegerInput(String prompt, Scanner scanner) {
        System.out.print(prompt);
        int validInteger = -1;
        while (scanner.hasNext()) {
            if (scanner.hasNextInt()) {
                validInteger = scanner.nextInt();
                break;
            } else {
                System.out.println("Error: Invalid input, try again...");
                System.out.print(prompt);
                scanner.next();
            }
        }
        return validInteger;
    }
}

Example Usage:

Please enter an integer: a
Error: Invalid input, try again...
Please enter an integer: 😀
Error: Invalid input, try again...
Please enter an integer: 1.0
Error: Invalid input, try again...
Please enter an integer: 6
You entered: 6
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.