I need to check users input. I have a menu and I need the user to select numbers 0-4 but if the user selects a letter instead of a number then I just get a InputMismatchException. So I am trying to validate that the user entered a number. Here is my code:
public class TestBankAccount {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
ArrayList<BankAccount> list = new ArrayList<BankAccount>();
int choice;
do {
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.println("4. Create new account");
System.out.print("Your choice, 0 to quit: ");
choice = input.nextInt();
switch (choice) {
case 1:
depositMoney(list);
break;
case 2:
withdrawMoney(list);
break;
case 3:
checkBalance(list);
break;
case 4:
createNewAccount(list);
break;
case 0:
System.out.println("Thank you for trusting us with your banking needs!");
break;
default:
System.out.println("Invalid option is selected!");
}
System.out.println();
} while (choice != 0);
if (list.size() > 0) {
displayResults(list);
}
}
I was thinking to do something like while (choice != 0 && choice != input.hasNextInt()); but I get an error. Any ideas?