首页 > 解决方案 > 切换while循环

问题描述

我有一个使用开关实现对应用程序菜单控制的基本方法

 public void applicationMenu(String input) {
    switch (input) {
        case "1":
            findGroups();
            break;
        case "2":
            findStudentsByCourseName();
            break;
        case "3":
            addNewStudent();
            break;
        case "4":
            deleteStudentById();
            break;
        case "5":
            addStudentToCourse();
            break;
        case "6":
            removeStudentCourse();
            break;
        default:
            printDefault();
            break;
    }
}

我使用这个方法和一个while循环来调用我的应用程序菜单

public void callMenu() {
        boolean exit = false;
        while (!exit) {
            viewProvider.printMainMenu();
            String input = viewProvider.readString();
            if (input.equals("7")) {
                exit = true;
            }
            applicationMenu(input);
        }
    }

如何触发 switch case 的退出但同时保持两种方法的结构?

标签: javawhile-loopswitch-statement

解决方案


这应该有效:

public boolean applicationMenu(String input) {
    boolean shouldContinue = true;
    switch (input) {
        case "1":
            findGroups();
            break;
        case "2":
            findStudentsByCourseName();
            break;
        case "3":
            addNewStudent();
            break;
        case "4":
            deleteStudentById();
            break;
        case "5":
            addStudentToCourse();
            break;
        case "6":
            removeStudentCourse();
            break;
        case "7":
            shouldContinue = false;
            break;
        default:
            printDefault();
            break;
    }
    return shouldContinue;
}

...

public void callMenu() {
    while (true) {
        viewProvider.printMainMenu();
        String input = viewProvider.readString();
        if (!applicationMenu(input)) {
            break;
        }
    }
}

推荐阅读