Im currently trying to build a code that prevents wrong user input (storing a char/string to a integer, e.g.) but Im not being able to make it to work...
public static void main(String[] args) {
int num=0, option=0;
boolean keep=true;
Scanner scan = new Scanner(System.in);
while(keep) {
System.out.println("1 - Test Exception.");
System.out.println("2 - Out.");
option = scan.nextInt();
switch(option) {
case 1:
System.out.println("Write a number: ");
if(scan.hasNextInt()) {
num = scan.nextInt();
}
else {
System.out.println("Wrong input...");
}
break;
case 2:
keep=false;
System.out.println("Bye !");
break;
}
}
}
As soon as I input a char/string, the code stops working. The exception occurs in the line option = scan.nextInt();
What am I missing?