I am writing a simple program to get user input from Scanner to perform some tasks,
I want to get user input only from the number 1 to 3,
any negative number or string will display an error message and prompt user to re-enter.
Here's comes the problem...
When I enter String, it display proper error message -> "Invalid, enter again : "
However, when I enter any number less than 0 or more than 3,
it display the error message of -> "Enter option: "
Another problem, let say if I enter negative number, e.g. -123
then when I enter String, the error message "Invalid, enter again : " will immediately show twice...
My coding...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
byte option;
do {
System.out.print("Enter option: ");
while (!scan.hasNextByte()) {
System.out.print("Invalid, enter again : ");
scan.nextLine();
}
option = scan.nextByte();
} while (option < 0 || option > 3);
switch (option) {
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
case 3:
System.out.println("3");
break;
default:
break;
}
}
}
Need help to solve the problem, which all the error message is display "Invalid, enter again : "
Thanks.