java - 切换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 的退出但同时保持两种方法的结构?
解决方案
这应该有效:
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;
}
}
}
推荐阅读
- c++ - 拥有 [[nodiscard]] 类型的理由是什么?
- .net - 是什么导致我的 Entity Framework Core dbContext 泄漏内存?
- java - 从数据库中获取数据并将其显示在回收站视图中的 Viewpager 中
- c# - 在 Datastax CassandraCSharpDriver.Graph 中向现有顶点添加新顶点和边,但出现边 OUT 错误
- django - django如何在导出到csv之前过滤数据
- c# - 正在使用的多播侦听器端口
- sql - SQL 为 EXEC 存储过程提供另一个带有撇号参数的存储过程
- php - php默认从url获取id
- java - 如何使用 Mockito 在另一个方法中调用一个方法
- php - 放置文件时 created_at/updated_at 为空