highlandertf2
highlandertf2

Reputation: 51

Java - How do I check if a Scanner input is an integer without using a while loop?

I have written a program for one of my assignments which asks for an input to assign to an integer variable. One of the parts of the assignment is, if the integer input is anything other than 1, 2, 3, or 4, the program should print a statement saying that is an invalid input, then end the program.

I have figured out how to get it to print this statement if the user enters an input higher than 4 or lower than 1, but I can not figure out how to get the same result when a double is entered.

I have managed to make it work by using a while loop that checks if the input is an integer or not,

while (!input.hasNextInt()){
    System.out.println("Invalid choice. Good-bye.");
    input.next();
}
int selection = input.nextInt();

I would like it to recognize it as an invalid input and then end the program right there. Instead, it waits for another valid input from the user

Expected result, per the assignment: " If the user enters anything other than 1, 2, 3, or 4, the program should print, "Invalid choice. Good-bye." "

Upvotes: 1

Views: 429

Answers (1)

forpas
forpas

Reputation: 164099

You did not mention what happens when a valid number is entered or the user enters anything other than an integer number.
So this code will exit the program when the user enters a non integer value or an integer not between 1 and 4:

Scanner input = new Scanner(System.in);
int number = 0;
boolean valid = false;
System.out.println("Enter number: ");
if (input.hasNextLine()) {
    if (input.hasNextInt()) {
        number = input.nextInt();
        if (number >= 1 && number <= 4) {
            valid = true;
            System.out.println("Valid choice:" + number);
        }
    }
    input.nextLine();
    if (!valid) {
        System.out.println("Invalid choice. Good-bye.");
        System.exit(0);
    }
}

Upvotes: 1

Related Questions