java中的什么代码可以在CMD中退出程序或结束程序?

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

如何结束我的程序?

我尝试了 3 次让用户回答某个答案,但如果用户回答错误并使用了所有 3 次尝试。我怎样才能让程序结束?

这是我的代码:

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..");
            }
        }

游戏结束后,虽然游戏本应结束,但程序仍继续进行下一题。它的代码是什么?

您需要break。我在 if ( attempts1 == 0 ) 中添加了它。现在应该可以解决您的问题了。

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.." );
                break;
            }
        }

你可以使用

System.exit(0);

0 表示程序正常退出,如果出现异常终止或您可以使用 1 或其他特定的非零状态代码。

您正在尝试在循环中检查正确答案的输入值,因此每次都将其添加到循环中进行检查是多余的:

您可以在使用 break 关键字或 3 次错误尝试找到正确答案后关闭应用程序:

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

根据您发布的代码,我猜还有另一个更大的循环遍历问题。所以你也需要用一个标志来停止更大的循环。像这样的东西:

for (String answer1: answers) {
        boolean gameOver = false;
        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..");
                gameOver = true;
            }
        }
        if (gameOver) {
            break;
        }
    }

有很多使用 System.exit(...) 的建议 - 如果有充分的理由,这在技术上是退出应用程序的正确方法。但是,在您的情况下,您有一个应该退出的循环,但它不起作用 - 这表明问题出在您的循环条件中。

其他任何事情,无论是中断还是 System.exit(...) 调用都只是绕过了其他地方确实存在问题的事实。

话虽如此 - 如果我 运行 您的代码与原样完全一样,它的行为就会符合预期。那么我们看不到的其他代码是什么?