如何使用增强的for循环和数组进行骰子游戏

时间:2016-12-12 19:31:30

标签: java dice

好的,对于一个项目,我需要像用户想要的那样循环通过尽可能多的骰子滚动并将它们存储在一个数组中,最后用高级for循环打印出来。我已完成其他所有工作,但我仍然坚持如何将数组/高级for循环集成到现有代码中。

这是用于处理所有骰子功能的类:

package paradiseroller;

public class PairOfDice
{
    public int sides = 6;
    public int die1;   // Number showing on the first die.
    public int die2;   // Number showing on the second die.

    public PairOfDice()
    {
        // Constructor.  Rolls the dice, so that they initially
        // show some random values.
        roll();  // Call the roll() method to roll the dice.
    }

    public void roll()
    {
        // Roll the dice by setting each of the dice to be
        // a random number between 1 and 6.
        die1 = (int) (Math.random() * sides) + 1;
        die2 = (int) (Math.random() * sides) + 1;
    }

    public int getDie1()
    {
        // Return the number showing on the first die.
        return die1;
    }

    public int getDie2()
    {
        // Return the number showing on the second die.
        return die2;
    }

    public int getTotal()
    {
        // Return the total showing on the two dice.
        return die1 + die2;
    }
}

这是我需要使用数组和for循环的主文件:

package paradiseroller;

import java.util.ArrayList;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        String choice = "y";
        Scanner sc = new Scanner(System.in);

        while (choice.equalsIgnoreCase("y")) {
            PairOfDice dice;          // A variable that will refer to the dice.
            int rollCount;    // Number of times the dice have been rolled.

            dice = new PairOfDice();  // Create the PairOfDice object.
            rollCount = 0;

            System.out.println("\nIt took " + rollCount + " rolls to get a 2.");

            System.out.print("Would you like to continue? y/n");
            choice = sc.nextLine();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

只要您想要并将其存储在数组中然后打印,请将g设置为用户想要的数量

GameDelegate

想一想:因为它会得到每个int IN结果并将其分配给r进行每次迭代。

请记住,如果你想把它放在一个数组中(在这种情况下有点不好),如果你只是想立即打印那么就可以使用

PairOfDice[] result = new PairOfDice[g];

// setting
for (int i = 0; i < g; i++)
{
   result[i] = new PairOfDice();
}

// printing
for (PairOfDice r : result)
{
   System.out.println(r.getDie1() + " " + r.getDie2());
}

由于i,您还可以访问它所在的插槽。