3

I am creating a menu based program in java using switch case. here are 4 cases:

  1. add record
  2. delete record
  3. update record
  4. Exit

I added break after each case but, what I want to do is to terminate the program when user enter case no 4 so what to do in this case ?

Abhijit Kumbhar
  • 923
  • 3
  • 23
  • 49
  • @Solver you nailed it. – Wololo Aug 29 '15 at 17:55
  • Why down vote did I asked anything wrong ? – Abhijit Kumbhar Aug 29 '15 at 17:55
  • possible duplicate of [How to quit a java app from within the program](http://stackoverflow.com/questions/2670956/how-to-quit-a-java-app-from-within-the-program) – Madhawa Priyashantha Aug 29 '15 at 17:56
  • 1
    I think the reason for the downvotes is: generally, StackOverflow prefers questions that show that the asker has tried to solve the problem themselves and hit a problem or gotten stuck, instead of questions that look like the questioner just wants others to do the work for them. Your question is sort of on the fence and could be taken either way. Next time, try coding it yourself until you get stuck, then post the code that you've tried. You'll be a lot less likely to get downvotes. – ajb Aug 29 '15 at 23:46
  • How could anyone possibly suggest `System.exit(0);` – Ojonugwa Jude Ochalifu Mar 21 '22 at 09:24

8 Answers8

8

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.

ajb
  • 31,309
  • 3
  • 58
  • 84
6

If you do not wish to choose either return or System.exit(ExitCode) then put the termination condition in while loop as shown below.
Why to put while(true) and then put return or System.exit instead exploit the boolean check of the while loop to exit it.

private static void mainMenu() {
    int option=0;//initializing it so that it enters the while loop for the 1st time 
    while(option!=4){
        option = getOptionFromUser();
        switch(option) {
            case 1:
                addRecord();
                break;
            case 2:
                deleteRecord();
                break;
            case 3:
                updateRecord();
                break;
            case 4:
                System.out.print("While Loop Terminated");
                break;
        }
    }
    // when user enters 4,
    //Will execute stuff(here the print statement) of case 4 & then
    //... will come here you can do other stuff if desired
}
Riddhesh Sanghvi
  • 1,218
  • 1
  • 12
  • 22
1

You can use System.exit() for this purpose.

System.exit(int status)

Terminates the currently running Java Virtual Machine.

Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45
  • but what is status here – Abhijit Kumbhar Aug 29 '15 at 17:52
  • You can define your own status, for example you can pass `-1` and assume it was an error, or `0`when everything is okay. The status is just a variable to help you, you can end a program in several situations (for example errors), with this status variable you can decide your own error codes. Or you can pass no status at all. It's all your call. – Bruno Caceiro Aug 29 '15 at 17:56
  • @AbhijitKumbhar Please do not use `System.exit` for this purpose. I am appalled that there are so many answers recommending it. – ajb Aug 29 '15 at 18:24
1

Whenever You want to Exit out of the Switch case it is always better to use a do-while loop because that gives the user an advantage of running the Program again if he wants to update, delete or add Multiple records as in your Program

class record{
public static void main(String args[]){
do
{
System.out.Println("Enter Choice ");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
switch(option){
case 1:{
//Code for Adding the Records
break; 
}
case 2:{
//Code for deleting the Records
break;
}
case 3:{
//Code for Updating the Records 
break;
}
case 4:{
break; 
      }
   }
}
while(choice!=4);
    }
}

Wherever you want to add the Code for adding,deleting and updating the records you can call the Methods also which are defined outside the Switch Case and the Program should run just fine

Radhesh Khanna
  • 141
  • 3
  • 11
0

return OR System.exit(ExitCode) if you want to exit directly.

Shubham Chaurasia
  • 2,472
  • 2
  • 15
  • 22
  • @AbhijitKumbhar Please do not use `System.exit` for this purpose. I am appalled that there are so many answers recommending it. – ajb Aug 29 '15 at 18:25
0

In case no 4, add:

System.exit(int status);

Usually, status >= 0 indicates that the program terminated correctly and status < 0 indicates an abnormal termination. I think you should use:

System.exit(0);

status serves as errorCode. You can assign whatever value you want. If your program contains many exit points, you can assign different errorCodes to them. You can return the errorCode to the environment which called the application. Through this errorCode, you can trace which System.exit() caused the program to terminate.

Wololo
  • 841
  • 8
  • 20
  • @AbhijitKumbhar Please do not use `System.exit` for this purpose. I am appalled that there are so many answers recommending it. – ajb Aug 29 '15 at 18:24
0

Your particular case in your switch statement would be:

case 4: System.exit(0);
burglarhobbit
  • 1,860
  • 2
  • 17
  • 32
  • 1
    @AbhijitKumbhar Please do not use `System.exit` for this purpose. I am appalled that there are so many answers recommending it. – ajb Aug 29 '15 at 18:24
  • yes I saw your answer, seems more valid enough. I will make sure to use `return` during coding on my next Lab Assignments. Thank You. – burglarhobbit Aug 29 '15 at 18:29
  • @Mr.Robot you can also exploit the condition of while loop to attain the same. If you wish to avoid adding extra `return` or `System.exit`. – Riddhesh Sanghvi Aug 30 '15 at 08:23
  • @RiddheshSanghvi Yes, that would be the most simplest one. – burglarhobbit Aug 30 '15 at 10:25
-1

float ans;

    switch(operator)
    {
        case '+':
            ans = no1 + no2;
            break;

        case '-':
            ans = no1 - no2;
            break;

        case '*':
              ans = no1 * no2;
            break;

        case '/':
              ans = no1 / no2;
            break;
    case '0':
    System.exit(0);

        default:
            System.out.printf("EERRRoOOOORRR(^!^)");
            return;
    }