Okay so for a project I need to loop through as many dice rolls as the user wants and store them in an array to print out at the end with an advanced for loop. I have everything else done but I am stuck on how to integrate an array/advanced for loop into my existing code.
This is the class used to deal with all the dice functions:
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;
}
}
This is the main file in which I need to use the array and for loop:
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();
}
}
}
For going as long as you want and storing it in a array then printing, let g be the amount the user wants
Think of : as in so it's getting each int IN result and assigning it to r for each iteration.
Keep in mind this is for if you want to put it in a array (kinda bad in this case) if you just want to print immediately then you could use
This also gives you access to the slot that it's in thanks to i.