Please don't use System.exit
. It's like trying to use a chainsaw to slice a tomato. It's a blunt tool that might be useful for emergency situations, but not for normal situations like you're trying to write.
There are a couple better approaches: (1) If you put your loop in a method, where the method's only purpose is to read the user's input and perform the desired functions, you can return
from that method:
private static void mainMenu() {
while(true) {
char option = getOptionFromUser();
switch(option) {
case '1':
addRecord();
break;
case '2':
deleteRecord();
break;
case '3':
updateRecord();
break;
case '4':
return;
}
}
}
Now, whatever program calls mainMenu()
has an opportunity to do some cleanup, print a "goodbye" message, ask the user if they want to back up their files before exiting, etc. You can't do that with System.exit
.
Another mechanism, besides return
, is to use break
to exit the loop. Since break
also breaks out of a switch
, you'll need a loop label:
private static void mainMenu() {
menuLoop:
while(true) {
char option = getOptionFromUser();
switch(option) {
... as above
case '4':
break menuLoop;
}
}
... will go here when user types '4', you can do other stuff if desired
}
Or (as Riddhesh Sanghvi suggested) you can put a condition in the while
loop instead of breaking out of it. His answer used a condition based on the option
; another idiom I've used a lot is to set up a boolean
for the purpose:
private static void mainMenu() {
boolean askForAnother = true;
while(askForAnother) {
char option = getOptionFromUser();
switch(option) {
... as above
case '4':
askForAnother = false;
}
}
... will go here when user types '4', you can do other stuff if desired
}
Or:
private static void mainMenu() {
boolean done = false;
do {
char option = getOptionFromUser();
switch(option) {
... as above
case '4':
done = true;
}
} while (!done);
}
So you have a lot of options, all better than System.exit
.