2

因此,我正在制作一个简单骰子游戏的副本,该游戏是 Maxwell Sanchez YouTube JAVA on Eclipse 教程中的一个示例。我开始玩的是实现基于文本的菜单的简单方法。

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

我现在的问题是,到目前为止一切似乎都正常,除了如果你到最后并键入 N 退出,它需要 N 的 2 个输入才能实际执行 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();
        }
}
}
4

2 回答 2

2

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

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()您都会阅读用户输入。

于 2015-02-03T05:27:01.840 回答
2
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")) 
于 2015-02-03T05:27:45.230 回答