Reputation: 13
I'm trying to verify that users input only 1, 2, or 3. So far I've used sc.hasNextInt() to validate integers, but not those specific ones. Can someone help? My code is below.
System.out.print("Enter Department Number: ");
while (!sc.hasNextInt())
{
System.out.println("Invalid entry. Please enter 1, 2, or 3 for the
department number.");
System.out.print("Enter Department Number: ");
sc.next();
}
int department = (sc.nextInt());
Upvotes: 0
Views: 398
Reputation: 2823
Your code should be:
System.out.print("Enter Department Number: ");
int department = sc.nextInt();
while(department != 1 || department != 2 || department != 3 ) {
System.out.println("Invalid entry. Please enter 1, 2, or 3 for the
department number.");
System.out.print("Enter Department Number: ");
department = sc.nextInt();
}
Upvotes: 1
Reputation: 17142
You can proceed like this:
Scanner sc = new Scanner(System.in);
int departement;
do {
System.out.print("Enter Department Number: ");
departement = sc.nextInt();
}while (departement != 1 && departement != 2 && departement != 3);
Upvotes: 0
Reputation: 383
Not very clean or coherent but
int input;
while(!sc.hasNextInt()||((input=sc.nextInt())>3&&input<1)))
Upvotes: 0
Reputation: 2199
Use a while loop where you ask for the next integer and only break when it is inside the correct range:
Code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int value;
while (true) {
System.out.print("Enter Department Number: ");
if (sc.hasNextInt()) {
value = sc.nextInt();
if (value < 1 || value > 3)
System.out
.println("Invalid entry... must be between 1 and 3");
else
break;
}
}
else
sc.next(); // does not block when a string is putted in
System.out.println(value);
}
Upvotes: 0
Reputation: 5588
Read entire line and check that it matches regular expression:
int department;
System.out.print("Enter Department Number: ");
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.matches("[123]")) {
System.out.println("Invalid entry. Please enter 1, 2, or 3 for the department number.");
System.out.print("Enter Department Number: ");
} else {
department = Integer.parseInt(line);
break;
}
}
Upvotes: 0
Reputation: 2466
You do not account for a String-to-Int Conversion or the newLine character left unconsumed.
while (sc.hasNextLine()) {
int choice = Integer.parseInt(sc.nextLine().trim());
if (choice == 1 || choice == 2 || choice == 3)
//do something
}
Upvotes: 1