程序在switch语句中使用try catch块后终止

时间:2016-04-28 00:18:10

标签: java switch-statement try-catch

以下代码在try catch block捕获异常后终止。不允许我从菜单选项中进行选择。所以我的问题是我必须对此代码进行哪些更改,以便我可以循环回来,以便我可以再次获得用户输入。

    public class Main {

        public static void main(String[] args) {

            Modify modifyObj = new Modify();

            int choice = 0 ;

           Scanner input = new Scanner(System.in);

            //begin loop
            do {
                 try{

                //display menu

                System.out.println("Choose one option from following option available: ");
                System.out.println("0) Exit program. ");
                System.out.println("1) Create a Roster");
                System.out.println("2) Modify a Roster");
                System.out.println("3) Delete a Roster");



                choice = input.nextInt(); //gets user input 

                    switch (choice) {

                        case 1:
//code
                         break;


                        case 2:
    //code
                                break;

                        case 3:
                            //code
                           break;


                    }// end of switch statement
                    break;
                }//end oftry
                 catch(InputMismatchException inputMismatchException){
                    System.out.println("Enter integer  value between 0 and 7:"); 
                    continue;
                 }


            }while (choice!=0); //loop until user exit 0.

        }//end of main
    }// end of Main class

1 个答案:

答案 0 :(得分:0)

choice

之前确保0不是continue;
catch(InputMismatchException inputMismatchException){
    System.out.println("Enter integer  value between 0 and 7:"); 
    choice = 1; // <-- not 0.
    continue;
}

注意默认 choice初始值为0

你可以使用方法

如果您将逻辑解析为一个(或两个)实用程序方法以显示菜单并获得用户的选择,那么它将简化操作;

之类的东西
private static void showMenu() {
    System.out.println("Choose one option from following option available: ");
    System.out.println("0) Exit program. ");
    System.out.println("1) Create a Roster");
    System.out.println("2) Modify a Roster");
    System.out.println("3) Delete a Roster");
}

private static int getUserOption(Scanner input) {
    while (true) {
        showMenu();
        if (input.hasNextInt()) {
            int t = input.nextInt();
            switch(t) {
            case 0: case 1: case 2: case 3:
                return t;
            }
        } else {
            input.nextLine();
        }
    }
}

然后你的main可以像

一样调用它
public static void main(String[] args) {
    Modify modifyObj = new Modify();

    Scanner input = new Scanner(System.in);
    int choice;
    // begin loop
    do {
        choice = getUserOption(input);
        if (choice != 0) {
            System.out.printf("You chose %d.%n", choice);
        }
    } while (choice != 0); // loop until user enters 0.
}// end of main