1 year ago
#388491
comms
How to check if input is not integer
So this is an infitine loop until number 6 is entered, if a number that is not a choice is entered it pritns the error and start the loop again. But, when the input is not an int it prints the menu over and over and it never stops. The program should print error aswell if something that is not an int is entered. help
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("enter 1 to print names");
System.out.println("enter 2 to add name");
System.out.println("enter 3 to clear all names");
System.out.println("enter 4 to save name to file");
System.out.println("enter 5 to load file names");
System.out.println("enter 6 to quit");
System.out.println("Please input the number of your choice: ");
try {
choice = sc.nextInt();
System.out.print("\n");
}
catch(InputMismatchException e) {
//invalid input entered, clear it,send error, and set option to 0
choice = 0;
}
switch (choice) {
case 1:
printNames();
break;
case 2:
sc.nextLine();
addName(sc);
break;
case 3:
clearNames();
break;
case 4:
sc.nextLine();
saveNames(sc);
break;
case 5:
sc.nextLine();
loadNames(sc);
break;
case 6:
System.out.println("program closed!");
break;
default:
System.out.println("Invalid choice.\n");
break;
}
} while(choice!=6);
java
do-while
0 Answers
Your Answer