我有一种基本的方法,可以使用开关来实现对应用程序菜单的控制
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);
}
}
如何触发切换案例的退出,但同时保持两种方法的结构?
这应该起作用:
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;
}
}
}
如评论中所述,您可能会引发Exception,但是如果我没有处于实际错误状态,我通常不愿意这样做。对我来说,使用返回值并评估结果以确定程序是否应终止是更有意义的:
public void callMenu() {
boolean exit = false;
while (!exit) {
viewProvider.printMainMenu();
exit = applicationMenu(viewProvider.readString());
}
}
public boolean applicationMenu(String input) {
switch (input) {
case "1":
findGroups();
return false;
case "2":
findStudentsByCourseName();
return false;
case "3":
addNewStudent();
return false;
case "4":
deleteStudentById();
return false;
case "5":
addStudentToCourse();
return false;
case "6":
removeStudentCourse();
return false;
case "7":
return true;
default:
printDefault();
}
return false;
}