Search code examples
javaexit

What code in java do I use to exit program or end program in CMD?


How do I end my program?

I made 3 attempts for the user to answer a certain answer, but if the user incorrectly answered and used all the 3 attempts. How could I make the program end?

Here is my code:

while (attempts1-- > 0 && !answer1.equals(ans1))
        {
            System.out.print("What is your guess? ");
            ans1 = sc.next();
            
            if (ans1.equals(answer1)) {
                System.out.println("You guessed correctly!");
                attempts1 = 3;
            }
            else {
                System.out.println("Incorrect. Attempts remaining: " + attempts1 + " What is your guess again?");
            }
            if (attempts1 == 0) {
                System.out.println("Game over..");
            }
        }

After the game over, the program still continues to the next question even though the game is supposed to end. What's the code for it?


Solution

  • You could use

    System.exit(0);
    

    The 0 indicates the program exited gracefully, if there were an abnormal termination or something you could use 1 or another specific nonzero status code.