Я новичок в программировании, и в настоящее время я пишу меню для банка.Как заставить мою программу обрабатывать другие символы, вводимые пользователями? в то время как/примерочных улов? (java)
Пользователь может выбрать, является ли он администратором или клиентом, нажав 1 или 2. Я хочу написать код, чтобы, если пользователь вводит другие символы, чем ints
, программа отправит сообщение об ошибке и позвольте пользователю снова выбрать.
До сих пор мне удалось получить программу для обработки других целых чисел, чем 1 и 2, с использованием цикла while
.
Я думаю, что я должен использовать try
и catch
, но я не могу заставить его работать. Я отметил, где я пробовал try
/catch
с //----------
.
пользовательского ввода Х вместо номера:
run:
Press 1 to login as customer or 2 to login as admin x
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at bank.Bank.main(Bank.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)
public class Bank {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int ChoiceOne;
int CustpNr;
int CustChoice;
int AdminpNr;
int AdminChoice;
System.out.print("Press 1 to login as customer or 2 to login as admin ");
ChoiceOne = input.nextInt();
while (ChoiceOne != 1 && ChoiceOne != 2) {
// ---------------
try {
ChoiceOne = input.nextInt();
} catch (Exception e) {
continue;
}
// ----------------
System.out.print(" Wrong number. Press 1 to login as customer or 2 to login as admin ");
ChoiceOne = input.nextInt();
}// ends while
// The code below generates a menu for the customer if the user chooses 1
// and a meny for the admin if the user chooses 2.
if (ChoiceOne == 1) {
System.out.print("Welcome customer. Please login by using your birthdate (yymmdd) ");
CustpNr = input.nextInt();
boolean quit = false;
do {
System.out.println("1. deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
CustChoice = input.nextInt();
switch (CustChoice) {
case 1:
// deposit money
break;
case 2:
// withdraw money
break;
case 3:
// Check balance and accounts
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
} else if (ChoiceOne == 2) {
System.out.print("Welcome Admin. Please login using your birthdate (yymmdd) ");
AdminpNr = input.nextInt();
boolean quit = false;
do {
System.out.println("1. Add customer");
System.out.println("2. Add account");
System.out.println("3. List customer and accounts");
System.out.println("4. Remove customer");
System.out.println("5. Remove account");
System.out.print("Your choice, 0 to quit: ");
AdminChoice = input.nextInt();
switch (AdminChoice) {
case 1:
// add customer
break;
case 2:
// add account
break;
case 3:
// List customer and accounts
break;
case 4:
// ta bort kund
break;
case 5:
// ta bort konto
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}
}
}
Выглядит правильно - в чем проблема? – Mureinik
@Henrik Я отправил свой ответ lemme, знаю, если это вам поможет :) –
Извините, я не добавлял сообщения об ошибках при запуске программы, когда я впервые разместил вопрос. Если я запустил программу и введите «x» или другой символ, он сработает. – Henrik