-5

I want to terminate my program when input is 5.

My program doesn't close while pressing 5.

Code snippet:

System.out.println("What do you want to do?");
System.out.println("1. Go north");
System.out.println("2. Go east");
System.out.println("3. Go south");
System.out.println("4. Go west");
System.out.println("5. Quit");
System.out.print("Enter command (1-5): ");
// get and return the user's selection
System.exit(0); // exit the menu
return s.nextInt();

How to change it any suggestions?

Sjon
  • 4,989
  • 6
  • 28
  • 46

5 Answers5

5

You are exiting the program before getting any input from the user.

Remove

System.exit(0);
Eran
  • 387,369
  • 54
  • 702
  • 768
3

The evil place is here;

System.exit(0); // exit the menu

But it exit full program execution. Just comment this line and you will see user input.

For more info follow the links:

Update:

You able to add if() condition for terminating program when user enter 5:

int input = Integer.parseInt(s.nextInt());
if (input == 5) {
   System.exit(0);
}
Community
  • 1
  • 1
catch23
  • 17,519
  • 42
  • 144
  • 217
2

The below line doesnt exit the menu rather terminates the program execution

System.exit(0); // exit the menu

so other parts of your code becomes un-reachable

Santhosh
  • 8,181
  • 4
  • 29
  • 56
0

You may use a switch to exit on pressing 5 -

switch (int){
   case 1:
     //code for go north
    break;
 .
 . 
 .
 case 5:
    System.exit(0);
    break;

 default:
   break;

}
Razib
  • 10,965
  • 11
  • 53
  • 80
0

System.exit(int status) --> Terminates the currently running Java Virtual Machine.

After this statement we cannot execute other statements.

In your code you are using System.exit(0) before return statement.