Есть ли способ, которым я мог бы подсказать пользователю, какой штамп он хотел бы перекатить, и обновить переменные? - PullRequest
0 голосов
/ 26 марта 2019

Я создаю игру в кости, где 4 кубика бросаются через числа 0-6.После того, как они выпадут, я хочу спросить пользователя, хотят ли они перебросить 0, 1 или 2 своего кубика.У меня возникли проблемы с обновлением переменной d1, d2, d3, d4 (соответствующий кубик). Я не уверен, как правильно структурировать цикл while для достижения моей цели.У меня есть закомментированный код, потому что он не работает.Это будет повторять запрос пользователя и никогда не выходить из цикла while.Это также не будет обновлять переменные для выбранной кости.

Огромное спасибо за любую помощь.

Я пробовал, если, если-еще, while, делать-пока циклы и операторы,Я думаю, что я не правильно их структурирую.

public class Program6b {

    public static void main (String[]args)
    {

        Scanner stdIn = new Scanner(System.in);

        // This next section is an introduction to what my program does. \\
        System.out.println("Welcome to Coulter's Dice Game!");
        System.out.println("---------------------------------------------");
        System.out.println("Any Quad and you win! (106 wins)");
        System.out.println("Any Triple and you win! (6 wins)");
        System.out.println("Any Two-Pair is a win! (4 wins)");
        System.out.println("Anything else and you lose. (1 loss)");
        System.out.println("---------------------------------------------");
        System.out.println();
        System.out.println("Type anything to roll your first die.");
        String dontMindMe = "";
        dontMindMe = stdIn.next();
        System.out.println();
        System.out.println("---------------------------------------------");
        System.out.println();

        int d1, d2, d3, d4; // Int variables for 4 die.

        int wins = 0, loses = 0; // Keeps track of wins and loses.

        int rounds = 0; // Keeps track of rounds played.

        String playAgain = ""; // String to store if the user would like to play again.

        boolean win = false; // Boolean to determine if the player one.

        String rerollOne, rerollTwo;

        do
        {
        rounds = rounds + 1; // Adds 1 round every time the program is looped.

        d1 = (int)(Math.random() * 6) + 1; 
        d2 = (int)(Math.random() * 6) + 1; 
        d3 = (int)(Math.random() * 6) + 1; 
        d4 = (int)(Math.random() * 6) + 1;

        System.out.println("  Player ");
        System.out.println("----------");
        System.out.println(d1 + "  " + d2 + "  " + d3 + "  " + d4); // Outputs the dice rolls.
        System.out.println();

        win = false; // Resets the win boolean to false.

        // This next section asks the user if they would like to re-roll their dice
        int choice;

        /* System.out.println("How many dice would you like to reroll? (0,1,2): "); 
        choice = stdIn.nextInt();
        while (choice !=  0)
        {

            if (choice == 1)
            {
                System.out.println("What is the one die you would like to reroll? (d1, d2, d3, d4): ");
                rerollOne = stdIn.next();
                System.out.println();
                if (rerollOne == "d1")
                {
                    d1 = (int)(Math.random() * 6) + 1; 
                }
                else if (rerollOne == "d2")
                {
                    d2 = (int)(Math.random() * 6) + 1; 
                }
                else if (rerollOne == "d3")
                {
                    d3 = (int)(Math.random() * 6) + 1; 
                }
                else if (rerollOne == "d4")
                {
                    d4 = (int)(Math.random() * 6) + 1;
                }

                System.out.println("  Player ");
                System.out.println("----------");
                System.out.println(d1 + "  " + d2 + "  " + d3 + "  " + d4); // Outputs the dice rolls.
                System.out.println();
            }

            else if (choice == 2)
            {
                System.out.println("What is the first die you would like to reroll? (d1, d2, d3, d4): ");
                rerollOne = stdIn.next();
                System.out.println();
                if (rerollOne == "d1")
                {
                    d1 = (int)(Math.random() * 6) + 1; 
                }
                else if (rerollOne == "d2")
                {
                    d2 = (int)(Math.random() * 6) + 1; 
                }
                else if (rerollOne == "d3")
                {
                    d3 = (int)(Math.random() * 6) + 1; 
                }
                else if (rerollOne == "d4")
                {
                    d4 = (int)(Math.random() * 6) + 1;
                }

                System.out.println("What is the second die you would like to reroll? (d1, d2, d3, d4): ");
                rerollTwo = stdIn.next();
                System.out.println();
                if (rerollTwo == "d1")
                {
                    d1 = (int)(Math.random() * 6) + 1; 
                }
                else if (rerollTwo == "d2")
                {
                    d2 = (int)(Math.random() * 6) + 1; 
                }
                else if (rerollTwo == "d3")
                {
                    d3 = (int)(Math.random() * 6) + 1; 
                }
                else if (rerollTwo == "d4")
                {
                    d4 = (int)(Math.random() * 6) + 1;
                }

                System.out.println("  Player ");
                System.out.println("----------");
                System.out.println(d1 + "  " + d2 + "  " + d3 + "  " + d4); // Outputs the dice rolls.
                System.out.println();
            }

            else
            {
                System.out.println("How many dice would you like to reroll? (0,1,2): ");
                choice = stdIn.nextInt();
            }
        } */

        // This next if, else if, and else statement determines what the player wins. \\
        if ( (d1 == d2) && (d2 == d3) && (d3 == d4) ) // Quad win (106 wins)
        {
            win = true;
            wins = wins + 106;
            System.out.println();
            System.out.println("Quad win! (106 wins added)");
        }
        else if ( (d1 == d2) && (d2 == d3) ||
                  (d1 == d2) && (d2 == d4) ||
                  (d1 == d3) && (d3 == d4) ||
                  (d2 == d3) && (d3 == d4) ) // Triple win (6 wins)
        {
            win = true;
            wins = wins + 6;
            System.out.println();
            System.out.println("Triple win! (6 wins added)");
        }
        else if (
                  (d1 == d2) && (d3 == d4) ||
                  (d1 == d3) && (d2 == d4) ||
                  (d1 == d4) && (d2 == d3) ) // Two pair win (4 wins)
        {
            win = true;
            wins = wins + 4;
            System.out.println();
            System.out.println("Two-pair! (4 wins added)");
        }

        if ( win ) // If statement to print out if the user won.
        {
            System.out.println();
            System.out.println("Yay! You won this dice round!");
            System.out.println();
        }
        else
        {
            ++loses; // Else statement to ass to the total loses and print out if the user lost.
            System.out.println();
            System.out.println("Bummer, that's a junker!");
            System.out.println();
        }

        do // Do-while to make sure the user enters 'y' or 'n'.
        {
        System.out.println("Would you like to play again? (y/n): ");
        playAgain = stdIn.next();
        } while (!(playAgain.equalsIgnoreCase("y") || playAgain.equalsIgnoreCase("n")));
        System.out.println(); // Creates an empty space to tidy the output up.
        } while (playAgain.equalsIgnoreCase("y"));

        // This next section displays the final total of wins and loses. \\
        System.out.println("---------------------------------------------");
        System.out.println();
        System.out.println("Here are your results:");
        System.out.println("Total Rounds: " + (rounds));
        System.out.println("Total Rounds Lost: " + loses);
        System.out.println("Total Wins: " + wins);


    }
}

Я бы хотел, чтобы у пользователя запрашивалось, если он хотел бы перебросить 1 или 2 кубика, и программа работала соответственно.Я ожидаю, что число обновлений будет соответствовать тому, что вводит пользователь.После того, как это будет сделано, я бы хотел, чтобы пользователю показали свои выигрыши, и спросил, хотят ли они играть снова.

1 Ответ

0 голосов
/ 26 марта 2019

Вы неправильно сравниваете строки в своих условных выражениях.Поскольку вы используете оператор == для сравнения строк, ваш код проверяет равенство ссылок.В ваших случаях это всегда будет оцениваться как ложное.

Например, измените это:

if (rerollOne == "d1")

На это:

if ("d1".equals(rerollOne))

Метод сравнения будет сравниватьсодержимое строк.

Кроме того, поскольку вы запрашиваете только новый choice в блоке else, вы застрянете, перекатываясь навсегда.Я предлагаю переместить подсказку для нового choice за пределами else, чтобы вы запрашивали новый выбор при каждой итерации цикла и просто полностью удаляли else.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...