I'm currently working on a basic (and as I can see, frequently assigned) java project in which I'm to create a program that simulates the rolling of dice. In my project I'm only simulating the rolling of two six sided die. Arrays need to be used in completing this task.
So far I have try/catch block that asks the user for the amount of rolls they would like to simulate and ensures that they give an integer input. This in turn creates the length of the array for the dice simulator. Up to this point my code works but now I am stuck on how to find the longest streak of consecutive sums within that array.
I'm pretty sure I need to be comparing my dieSum value for each roll against itself, and if dieSum == dieSum then increasing a variable for my current streak by 1. I'm just unsure of how to do this, I suspect I may have a problem because my dieSum variable isn't being stored into an array.
import java.util.Scanner;
public class RollThoseDice {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.println("MyNameHere");
System.out.println("ThirdProgram \n");
//Variable listing and initialization
int rollTotal = 0; //number of trials
int dieSum; //sum of the outcome of both dice per roll
//Try - Catch block to ensure positive integer input from user for rollTotal
System.out.println("***Welcome to the Dice Roll Probability Generator***");
while (true){
System.out.println("Enter how many dice rolls you would like to simulate: ");
try {
rollTotal = kbd.nextInt() + 1;
break;
} catch (Exception e) {
System.out.println("Please only enter a positive integer. Try again. ");
kbd.next();
}
}
int die1[] = new int[rollTotal]; //Variable for the first die
int die2[] = new int[rollTotal]; //Variable for the second die
int[] diceArray = new int[rollTotal];
for (int i=1; i<diceArray.length; i++ ) {
die1[i] = (int)(6.0*Math.random() + 1.0); //Generate random # between 1-6
die2[i] = (int)(6.0*Math.random() + 1.0);
System.out.println("***Roll " + i + "***");
System.out.print("Dice one rolled: " + die1[i] + ", dice two rolled: " + die2[i] + "\n") ;
dieSum = die1[i] + die2[i];
System.out.println("Total rolled was: " + dieSum + "\n");
}
}
}
Thanks a lot for taking a peek at this for me, and excuse my freshness to the site and programming in general.
You need to keep track of two more variables: int biggestStreak, currentStreak
(initialized with 1).
After you rolled the dice and and stored the variables, you can check if your roll is the same as the roll before and increase currentStreak
:
int lastDieSum = die1[i-1] + die2[i-1];
if (lastDieSum == dieSum) {
currentStreak++;
if (currentStreak > biggestStreak) {
biggestStreak = currentStreak;
}
} else {
currentStreak = 1;
}
The last bit now also stores the current streak in biggestStreak
if it is bigger than the biggest streak. Finally, the current streak is set back to zero when the value isn't the same anymore as the lastDieSum
.
I hope this helps!