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

How to use an enhanced for loop and an array for a dice game

好的,对于一个项目,我需要遍历用户想要的任意数量的骰子,并将它们存储在一个数组中,以便在最后使用高级 for 循环打印出来。我已经完成了其他所有事情,但我仍然坚持如何将 array/advanced for 循环集成到我现有的代码中。

这是class用来处理所有骰子的函数:

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();
        }
    }
}

想放多久就放多久,然后将其存储在数组中然后打印,设 g 为用户想要的数量

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());
}

想想 : 因为它获取每个 int IN 结果并将其分配给每次迭代的 r。

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

for (int i = 0; i < g; i++)
{
   dice = new PairOfDice();
   System.out.println(dice.getDie1() + " " + dice.getDie2());
}

这也让您可以访问它所在的插槽,这多亏了我。