Reputation: 145
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)
Upvotes: 1
Views: 160
Reputation: 425003
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"
Upvotes: 1
Reputation: 333
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;
}
Upvotes: 2
Reputation: 106410
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);
Upvotes: 2