System.exit(0) 在 else if 期间需要两个控制台输入

Two console inputs required to System.exit(0) during else if

所以我正在制作一个简单的骰子游戏的副本,该游戏是 Maxwell Sanchez YouTube JAVA 关于 Eclipse 教程的示例。我开始尝试的是实现各种基于文本的菜单的简单方法。

我想要完成的是重启程序或终止程序的 Y 或 N 输入法。我完全是个菜鸟,在学习了一点 Arduino 之后就来到了这里。我喜欢JAVA但是有很多地方我不明白

我现在的问题是,到目前为止一切似乎都正常,除了如果您到达最后并键入 N 退出,它需要 2 个 N 输入才能实际执行 else if 语句。那是一个错误吗?或者我只是错误地编写了我想要完成的程序。

import java.util.*;
public class diceGame 
{
static int money;
static Scanner in = new Scanner(System.in);
static Random random = new Random();
static String userName;
static String tryAgain;

public static void main(String[] args) 
{
    money = 1000;
    System.out.println("Welcome to this simple dice game! " +
            "Please enter your name.");
    String userName = in.nextLine();
    System.out.println("Hey " + userName + ".");
    rollDice();
}
public static void rollDice()
{
    System.out.println("You have " + money + " coins!");
    System.out.println("Please select a number (1-6) to bet on!");
    int betRoll = in.nextInt();
    System.out.println("Please place your bet!");
    int betMoney = in.nextInt();
    while (betMoney > money)
    {
        System.out.println("You don't have enough coins... you only " +
                    "have " + money + "coins.");
        System.out.println("Please place a realistic bet!");
        betMoney = in.nextInt();
    }

    int dice;
    dice = random.nextInt(6)+1;

    if (betRoll == dice)
    {
        System.out.println("You Win!");
        money+=betMoney*6;
        System.out.println("You have " + money + " coins.");
    }

    else
    {
        System.out.println("Snap! You lost your coins!");
        money-=betMoney;
        System.out.println("You have " + money + " coins.");
    }

    if (money <= 0)
    {
        System.out.println("You've lost all yer coins!");
        System.out.println("Play again?" + " Type y or n");

        if (in.next().equalsIgnoreCase("y")) 
        {
            System.out.println("Maybe you'll win this time!");
            money = 1000;
            rollDice();
        } 

        else if (in.next().equalsIgnoreCase("n")) 
        {
            System.out.println("Maybe next time...");
            System.exit(0);
        } 

        else
        { 
            System.out.println("Invalid character");
        }
    }

    else
        {
                rollDice();
        }
}
}

将输入存储在一个变量中,然后进行比较...否则您将不得不输入两次。

String choice = in.next();
if (choice.equalsIgnoreCase("y")) 
{
    System.out.println("Maybe you'll win this time!");
    money = 1000;
    rollDice();
} 
else if (choice.equalsIgnoreCase("n")) // <-- not in.next()

每次调用 in.next() 都会读取用户输入。

if (in.next().equalsIgnoreCase("y")) 
else if (in.next().equalsIgnoreCase("n")) 

在此代码中,您调用 in.next() 两次,每个条件调用一次,因此它将读取两个输入。

你需要把阅读和比较分开。

String input = in.next();
if (input.equalsIgnoreCase("y")) 
else if (input.equalsIgnoreCase("n"))