简体   繁体   中英

How to restrict user input to the integer 1 or 2 and not allow user to enter anything other than a integer in java?

I'm having so much trouble with this. I have tried multiple things but it still gives me an error message and crashes. I want to loop it until the user enters 1 or 2.

System.out.println("Please choose if you want a singly-linked list or a doubly-linked list.");
System.out.println("1. Singly-Linked List");
System.out.println("2. Doubly-Linked List");
int listChoice = scan.nextInt();
//Restrict user input to an integer only; this is a test of the do while loop but it is not working :(
do {
    System.out.println( "Enter either 1 or 2:" );
    listChoice = scan.nextInt();
} while ( !scan.hasNextInt() ); 

It gives me this error:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Main.main(Main.java:35)

Use nextLine instead of nextInt , and deal with the exception afterwards.

boolean accepted = false;
do {
    try {
        listChoice = Integer.parseInt(scan.nextLine());
        if(listChoice > 3 || listChoice < 1) {
            System.out.println("Choice must be between 1 and 2!");
        } else {
            accepted = false;
        }
    } catch (NumberFormatException e) {
        System.out.println("Please enter a valid number!");
    }
} while(!accepted);

You could try this with the Switch Case statement as well.

switch(listchoice)
{
    case 1:
    //Statment
    break;

    case 2:
    //statement
    break;

    default:
    System.out.println("Your error message");
    break;
}

Because the user can enter anything, you have to read in a line as a String:

String input = scan.nextLine();

Once you've done that, the test is easy:

input.matches("[12]")

All together:

String input = null;
do {
    System.out.println("Enter either 1 or 2:");
    input = scan.nextLine();
} while (!input.matches("[12]")); 

int listChoice = Integer.parseInt(input); // input is only either "1" or "2"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM