對於我的任務之一,我們應該嘗試捕獲一個InputMismatchException並告訴用戶輸入一個給定的選項(在這種情況下,它可以是1,2,3,4而沒有其他)。出於某種原因,每當我嘗試創建try catch塊時,它都會讓用戶輸入兩次輸入,並且仍然會使程序崩潰。這裏是我有:如何使用try catch java?
do {
Scanner menuOptions = new Scanner(System.in);
System.out.println("1. Get another card");
System.out.println("2. Hold hand");
System.out.println("3. Print statistics");
System.out.println("4. Exit"+ "\n");
System.out.println("Choose an Option: ");
int selectedOption = menuOptions.nextInt();
try{
selectedOption = menuOptions.nextInt();
}
catch(InputMismatchException e){
System.out.println("Invalid input! Please select between options 1,2,3,4")
}
if (selectedOption == 1) {
//proceeds to do what is instructed if user input is 1}
else if (selectedOption ==2{
//proceeds to do what is instructed if user input is 2}
else if (selectedOption == 3) {
//proceeds to do what is instructed if user input is 3}
else if (selectedOption ==4{
//proceeds to do what is instructed if user input is 4}
任何想法,我怎麼能使這項工作?
[看看這個答案]( https://stackoverflow.com/questions/12702076/java-try-catch-with-inputmismatchexception-creates-infinite-loop) 希望這會有所幫助! –