Reputation: 81
I have a basic method that implements controlling of application menu using switch
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;
}
}
I use this method with a while loop to call my application menu
public void callMenu() {
boolean exit = false;
while (!exit) {
viewProvider.printMainMenu();
String input = viewProvider.readString();
if (input.equals("7")) {
exit = true;
}
applicationMenu(input);
}
}
How can I trigger exit from switch case but keep the structure of two methods at the same time?
Upvotes: 0
Views: 57
Reputation: 7868
As stated in comments, you could throw an Exception, but I typically don't like to do that if i'm not in an actual error state. It makes more sense to me to use a return value and evaluate the result to determine if the program should terminate:
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;
}
Upvotes: 0
Reputation: 67044
This should work:
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;
}
}
}
Upvotes: 1