Im trying to create an enhanced game of pig, where the user can roll a user entered number of dice. if all the dice rolled were a one, then you lose your bank points, if on of them is one, you get no points and your bank is safe. otherwise, you get to bank the points you rolled. I'm trying to loop through a queue in order for each player to get their turn, but it just loops the same person in the queue asking for how many dice the player wants to roll, then gets a result and terminates. What am i doing wrong here?
Also here's the current console output:
import java.util.Scanner;
import java.util.stream.IntStream;
import javax.lang.model.element.Element;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class EnhancedGameOfPig {
static int count;
static int roll() {
return (int) (6.0 * Math.random()) + 1;
}
public static void play() {
Scanner sc = new Scanner(System.in);
Queue<Player> myQueue = new LinkedList<Player>();
System.out.println("How many players are there? (2-10 Max)");
int numOfPlayers = sc.nextInt();
sc.nextLine();
for (int i =0; i < numOfPlayers; i++) { // creates specified number of
// players and adds
// them to a queue
System.out.println("What is your name player " + (i+1) + "?");
String playerName = sc.nextLine();
Player player = new Player(playerName, 0);
myQueue.add(player);
}
System.out.println("How many points would you like to play to, to win?"); // sets
// the
// number
// of
// points
// required
// to
// win
// the
// game
int maxPoints = sc.nextInt();
sc.nextLine();
for (Player e : myQueue) {
System.out.println("How many dice would you like to roll " + myQueue.peek().getPlayerName() + " ?");
int numofDice = sc.nextInt();
sc.nextLine();
int[] diceArray = new int[numofDice]; // creates an array to hold
// values of each dice roll
for (int i = 0; i <= numofDice-1; i++) {
diceArray[i] = roll(); // rolls dice and adds dice roll values
// to array
if (diceArray[i] == 1) {
count++;
}
}
int first = diceArray[0]; // looks at first value of array
for (int element : diceArray) {
if (element == first && first == 1) { // checks to see if all
// rolls were 1's
System.out.println("All of the dice you rolled were ones! You loose all your banked points!");
myQueue.peek().setBankedPoints(0);
break;
}
}
if (count == 1) {
System.out.println("You rolled a one, so you don't get any points. Sorry!");
} else {
int sum = IntStream.of(diceArray).sum();
System.out.println(sum + " points have been added to your bank!");
myQueue.peek().bankedPoints += sum;
}
}
}
}
Your loop control iterates through each player in the queue.
for (Player e : myQueue) {
But throughout your loop body your refer only to first player in the queue, with myQueue.peek(). For example:
System.out.println("How many dice would you like to roll "
+ myQueue.peek().getPlayerName() + " ?");
The peek() method returns the first player in the queue, but you're trying to affect the player e. You can address this problem by using e instead of myQueue.peek(), throughout the loop body.
Related
I'm trying to write a java code with(bingo game),(bullseye game)
the rules are simple:
computer picks 4 numbers
user input 4 numbers
must check the user input is between 1 to 10
If the user input exists in the computer randomized numbers it will be 1 bulls
If a number exist in the same location of the computer randomized number it will show 1 "eye"
Max limit is 20 tries until the user is considered "failed"; I need to print each round how many bulls were and how many eye were by the user input;
Example:
if the pc randomizing 1 4 6 7
and the user type 3 4 1 7
the output will be 3 bulls and 2 eyes.
my code prints 0 and 0 at the end.
Thanks for the help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
int[] pcGuess = new int[4];
int[] playerGuess = new int[4];
int countGuess = 0, bulls = 0, eye = 0;
final int maxGuess = 20;
System.out.println("Please press enter to begin");
in.nextLine();
boolean areNumbersCorrect = true; // a boolean value to define if the user input are correct (values between 1 to 10)
for (; countGuess < maxGuess; countGuess++) {
System.out.println("Please enter 4 numbers between 1-10");
for (int i = 0; i < playerGuess.length; i++) {
playerGuess[i] = in.nextInt();
pcGuess[i] = r.nextInt(10)+1;
if (playerGuess[i] < 0 || playerGuess[i] > 10) { // an if statement to check if the user input are correct
areNumbersCorrect = false;
do { // do while loop if the boolean is not true. (force the user to enter correct values)
System.out.println("Please try again");
for (int j = 0; j < playerGuess.length; j++) {
playerGuess[j] = in.nextInt();
if (playerGuess[j] > 0 && playerGuess[j] < 10) {
areNumbersCorrect = true;
continue;
}
}
} while (!areNumbersCorrect); // end of do while loop
}
for (int j=pcGuess.length; j>0; j--) { // for loop to check each number from the user and computer.
if (playerGuess[i] == pcGuess[i]) {
eye++; // if the user number exist in the same location evaluate eye++
if (playerGuess[i]%pcGuess[j]== 0) {
bulls++; // if the user number exist in the randomized number but not in the same location evaluate bulls++
}
}
}
System.out.println(
eye+" Hits!(same pc number and location)"+" And: "+bulls+" Numbers exist");
} if(eye==4&&bulls==4) {
break;
}
}
System.out.println("It took you: "+countGuess+" Times to guess the numbers");
}
}
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
ArrayList<Integer> randNumbers = new ArrayList<>();
Random random = new Random();
String input;
int number;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please press enter to begin");
input = sc.nextLine();
}while (!input.equals(""));//loop while user doesn't press ENTER
for (int i = 0; i < 4; i++){
randNumbers.add(random.nextInt(10) + 1);//loop to fill the randNumbers arraylist with random numbers
}
/*
randNumbers.add(3);
randNumbers.add(2);
randNumbers.add(9);
randNumbers.add(9);
*/
System.out.println("My random numbers: " + randNumbers.toString());
int counter = 0;
int bulls = 0;
int eyes = 0;
do {
System.out.println("Please enter 4 numbers between 1-10");
number = sc.nextInt();
if (number > 0 && number <= 10){
//System.out.println("index of rand: " + randNumbers.indexOf(number));
//System.out.println("count: " + counter);
if (randNumbers.indexOf(number) == counter){
eyes++;
System.out.println("eyes++");
}else if (randNumbers.contains(number)){
bulls++;
System.out.println("bulls++");
}
counter++;
System.out.println("Number " + counter + " introduced. " + (4 - counter) + " more to go.");
}else {
System.out.println("Wrong number.");
}
}while (counter < 4);//loop for user to introduce valid numbers
System.out.println("You scored " + bulls + " bulls and " + eyes + " eyes.");
}
}
Try this piece of code. Note that I used ArrayList rather than an array, as it offers methods such as .contains() and .indexof().
WARNING: Code will fail if the randNumbers arraylist contains two numbers that are equals, such as the 3-2-9-9 array that is commented when you input 9-9-9-9 as your number guesses. This is because .indexof() method:
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
Meaning the code fails to account the last 9 as it will compare the count index (3) to the first occurrence of 9 in the randNumbers, which is 2, making it false and not increasing eyes count.
Since I'm short on time, and this is an assigment you have and just copying it won't teach you much, I'll leave it to you to solve this specific case (I already told you what's wrong, won't be difficult to solve).
I have made a Dice game in Java using two files. The code runs perfectly, but it seems to have a logical error in it that I don't understand. In the game, it only outputs the same value as the previous roll. So if the die rolled a 6 and you rolled again, it would say you rolled a 6 again continuously. I'm trying to fix it currently but am having trouble. Any help would be greatly appreciated.
Here are the two programs:
import java.util.Scanner;
public class DiceGameTest {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//declare instance variables
int choice = 0;
//int total;
//total = die1.getRoll() + die2.getRoll();
//create the 2 die
Dice die1 = new Dice();
//Dice die2 = new Dice();
//print out description of game
System.out.println("Welcome to Eric and John's Dice game!");
System.out.println("This dice game is very simple, here are the rules!");
System.out.println(" 1. Roll a die");
System.out.println(" 2. To win, you must get a 4 or higher");
System.out.println(" 3. Have Fun!\n");
//ask the user if they want to roll the dice or quit
System.out.println("Would you like to roll the die to start playing? Press 1 to roll or \"-1\" to quit");
//user's choice
choice = input.nextInt();
//if the user puts 1
if(choice == 1)
{
System.out.printf("You rolled a %d%n", die1.getRoll());
}
//play the game
do
{
die1.getRoll();
if(die1.getRoll() >= 4)
{
System.out.println("Hooray! You won by getting a: " + die1.getRoll());
}
else if(die1.getRoll() < 4)
{
System.out.println("Too Bad! Your roll was: " + die1.getRoll() + " and it was not greater than or equal to 4");
}
//ask the user if they want to roll the dice again or quit
System.out.println("Would you like to roll the die to start playing? Press 1 to roll or \"-1\" to quit");
//user's choice
choice = input.nextInt();
}while(choice != -1);
if(choice == -1)
{
System.out.println("You Quit the Game!");
}
}
}
And this
import java.util.Random; //class used to generate random number for dice roll
public class Dice {
private int numberSides;
private Random randomGenerator;
private int currentRoll;
//default constructor
Dice() {
randomGenerator = new Random(); //initialize random object
numberSides = 6; //default number of sides
currentRoll = randomGenerator.nextInt(numberSides)+1; //initialize roll (1-6)
}
public int getRoll() {
return currentRoll;
}
//"roll" a random integer between 1 and numberSides
public void roll() {
currentRoll = randomGenerator.nextInt(numberSides)+1; //reroll 1-6
}
}
Right now you just keep calling die1.getRoll at the beginning of your loop. That number is not changing unless you call roll.
Remove currentRoll from your constructor. You don't need to put it there. Then,
die1.getRoll()
Should be,
die1.roll()
In your do while loop like this
do
{
die1.roll();
if(die1.getRoll() >= 4)
{
System.out.println("Hooray! You won by getting a: " + die1.getRoll());
}
else if(die1.getRoll() < 4)
//rest of it
Alternatively, you could make a few modifications in your game and change your function.
public int getRoll()
{
roll();
return currentRoll;
}
Why does my Java dice game keep repeating its roll?
You keep getting the same random number because the only code which is responsible for generating a new random number lies in the constructor of your Dice class.
The constructor will only be invoked once upon instantiation. Calling getRoll() subsequently will just return you the same random number.
If you want to receive a new random number from getRoll(), you can do it as:
public int getRoll(){ //return a new dice roll every time
return (randomGenerator.nextInt(numberSides)+1);
}
If you like the Dice class to "remember" the current roll, you can have a method like:
public int roll(){ //return a new dice roll every time & save current
currentRoll = randomGenerator.nextInt(numberSides)+1;
return currentRoll;
}
How would I go about calling the roll()function a getRoll() function? Could you please specify?
You don't need both roll() and getRoll(), either one is enough to generate a new random number. You just have to make sure you are placing randomGenerator.nextInt(numberSides)+1 in your roll() or getRoll() method to make it work.
I am currently teaching my self some basic Java through a text book and gave myself a "homework problem" but I'm having difficulty when writing to a .txt file of a method. It doesn't want to take more than 2 people. Here's a quick run down of what the method is meant to do:
1.) Collects the number of people the user would like to enter into the data file
2.) Collects the first and last name of each person in a two-dimensional array
3.) Collects a number of payments set by the user for each (separate) person that the user entered into an array.
4.) Then it calculates the average payment for each of the people entered into another array(so each person should have their own average)
5.) Lastly, it writes the data to a .txt file named "BusinessData.txt."
It seems to be working perfectly up until it tries to write more than 2 people into the .txt file. It's driving me nuts and I really would like to know how to fix this before moving on to the next couple of topics.
Here's the error message that I am getting when I try to add more than 2 people:
Exception in thread "main" java.lang.Array IndexOutofBoundsException:
3
at Business1.dataCollect(Business1.java:210)
at Business1.main(Business1.java:62)
I'd greatly appreciate any tips.
Here's the actual code:
import java.util.*;
import java.io.*;
public class Business1
{
public static void main(String[] args) throws IOException
{
// Declare local variables
int menuChoice;
// Declare local objects
Scanner input = new Scanner(System.in);
// Display the program title
System.out.println("\n\n\n\n\t\t\t\t***************************************\n"
+ "\t\t\t\t* Average Customer Payment Calculator *\n"
+ "\t\t\t\t***************************************\n\n\n");
// Start of a do-while loop: Continues the program as long as the user doesn't choose to exit
do
{
// Start of a do-while loop: Input Validation (menuChoice must be between 1 - 4)
do
{
// Prompt user for menuChoice
System.out.print("\tPlease enter an integer in accordance to the given choices:\n\n"
+ "\t(1) Collect and Erase Old Data\n"
+ "\t(2) Read Saved Data\n"
+ "\t(3) Append Old Data\n"
+ "\t(4) Exit Program\n\n"
+"\tEnter Choice: ");
menuChoice = input.nextInt();
System.out.println("\n\n");
// If menuChoice is equal to 1: Erase old Data and Collect and Write new data
if(menuChoice == 1)
{
try
{
dataCollect();
}
catch(IOException e)
{
System.out.println("Error");
}
}
// else if menuChoice is equal to 2: Read Saved Data
else if(menuChoice == 2)
{
}
// else if menuChoice is equal to 3: Append Old Data
else if(menuChoice == 3)
{
}
// else if menuChoice is equal to 4: Exit Program
else if(menuChoice == 4)
{
System.out.println("\n\n\n\t\tGoodbye!\n\n\n");
}
// else display error message: Error. Please enter a number 1 - 4
else
{
System.out.println("\n\nERROR. Please enter a number 1 - 4\n\n");
}
// End of do-while loop: Input Validation (menuChoice must be between 1 - 4)
} while(menuChoice < 1 || menuChoice > 4);
// End of a do-while loop: Continues the program as long as the user doesn't choose to exit
} while(menuChoice != 4);
}
// Create a method named dataCollect
public static void dataCollect() throws IOException
{
// Declare local variables
int numPeople, numPayments /* array size for payments */;
double totalPayments = 0, averagePayment;
double [] paymentsArray /* different payments */, averagePaymentsArray;
String [][] namesArray /* First name, last name in array */;
// Declare objects
Scanner keyboard = new Scanner(System.in);
// Prompt user for the number of people they would like to add to the records and store in variable numPeople
System.out.print("\tHow many people would you like to add to your records?\n\n\tEnter an integer: ");
numPeople = keyboard.nextInt();
System.out.println("\n\n");
// Initialize arrays
namesArray = new String[numPeople][2];
// Create a counter for the for-loop
int count = 0;
// For-loop will prompt user for first and last name of each person
for(int i = 1; i <= numPeople; i++)
{
// Consume the remaining newline character
keyboard.nextLine();
// Prompt user for first name
System.out.print("\tPlease enter the FIRST name of person #" + i +": ");
namesArray[count][0] = keyboard.nextLine();
System.out.println("\n\n");
//Prompt user for last name
System.out.print("\tPlease enter the LAST name of person #" + i + ": ");
namesArray[count][1] = keyboard.nextLine();
System.out.println("\n\n\n");
count++;
}
// Reset counter for the next for-loop
count = 0;
int count2 = 1; // Used to keep track of which payment number the user is inputing
int count3 = 0;
int count4 = -1;
// ****************************************************************
// * Open file for input ******************************************
// ****************************************************************
PrintWriter outputFile = new PrintWriter("BusinessData.txt");
outputFile.println("\t\t\tBusiness Data\n\n");
outputFile.println("First Name\tLast Name\tP 1\t\tP 2\t\t P 3\t\tAverage Payments\n\n"
+ "------------------------------------------------------------------------------------------------------------------------------------------------------\n");
// For-loop will ask for number of payments each person made while also collecting the value of each of those payments in a nested for-loop.
for(int i = 0; i < numPeople; i++)
{
// Prompt user for first name
System.out.print("\tPlease enter the number of payments made by " + namesArray[count][0] +" " + namesArray[count][1] + "(Put in 3 for now) : ");
numPayments = keyboard.nextInt();
System.out.println("\n\n");
// Initialize array then reset it for the next person to come
paymentsArray = new double[numPayments];
for(int j = 0; j < numPayments; j++)
{
// ****************************************************************
// * Open file for input ******************************************
// ****************************************************************
System.out.print("\n\n\tPlease enter payment value of payment #" + count2 + " that " + namesArray[count][0] +" " + namesArray[count][1] + " made: $");
paymentsArray[j] = keyboard.nextDouble();
System.out.println("\n\n");
// Increment counter
count2++;
}
// ************************************************************************
// * Calculating Average Payment ******************************************
// ************************************************************************
// For loop for calculating average
for(int k = 0; k < numPayments; k++)
{
totalPayments += paymentsArray[k];
}
// Calculate the Average Payment
averagePayment = totalPayments/paymentsArray.length;
/**************************************************
********** BUG LIES IN THE WRITING **************
***************************************************/
// nested for-loop will write data now otherwise it'll just be wiped out and overwritten by the next input
for(int l = 1; l < numPeople; l++)
{
// Increment counter4
count4++;
// Output first name
outputFile.print(namesArray[count4][count3]);
// Increment counter3
count3++;
// Output last name
outputFile.print("\t\t" + namesArray[count4][count3] + "\t\t");
// Reset counter3
count3 = 0;
for (int m = 0; m < numPayments; m++)
{
outputFile.print(paymentsArray[m] + "\t\t");
}
outputFile.println(averagePayment + "\n\n");
}
// Reset total Payments for the next iteration
totalPayments = 0.0;
// Increment the counter
count++;
}
outputFile.close();
// End of dataCollect method
}
Running your code gives me Exception for 3+ users.
ArrayIndexOutOfBoundsException thrown at
outputFile.print(namesArray[count4][count3]);
Running in debug mode shows that namesArray[count4][count3] is pointing to a value which is not available .
count4 is incremented to out of bounds value because of the below loop.
I don't undertstand why you need this loop
for(int l = 1; l < numPeople; l++)
{
enter code here}
If you remove this it works fine.
In the interest of learning I decided to write up a coin flipping program. The coin is an enum and i have the program return that enum value. I also have the user input from a menu style but this was helped by following along in a Barnes and Nobles book I purchased a while back.
I think I have come to a weird cross road. i was wanting to basically return the enum value and such but remove the 'menu' aspect and replace it with the ability for the user to input how many flips they would like to do and also repeat the program if they want to (so instead of pressing 1 to flip each time they can input say 20000 and it would flip that many times i also think doing this would help with a fairness check as a true test of fairness would return almost even amounts of heads and tails if it were to flip that many times then pressing 0 for no flips would end the program) and i want to prompt the user and ask if they would like to repeat.
here is the program I have written:
import java.util.*;
public class CoinTossing
{
private enum Coin { HEADS, TAILS };
private static final Random randomNumbers = new Random();
private static final int HEAD = 1;
private static final int TAIL = 2;
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
int choice;
int toss = 0;
int tosses = 0;
int frontflip = 0;
int backflip = 0;
Coin gameStatus;
System.out.println("Welcome to the Coin Toss Program.\n");
System.out.println("Choose from the menu what you want to do.");
System.out.print("1. Toss the coin\n2. Quit program\n");
choice = input.nextInt();
while ( choice != 0 )
{
if ( choice == 1 )
{
int CoinTossed = Flip();
switch ( CoinTossed )
{
//added tosses to switch statement to make the counter work perfect.
case HEAD:
gameStatus = Coin.HEADS;
tosses++; // add amount of tosses
break;
default: // changed case TAIL to default. Easy and works.
gameStatus = Coin.TAILS;
tosses++; // add amount of tosses
break;
}
if ( gameStatus == Coin.HEADS )
{
frontflip++; //Add amount of heads
}
else // gameStatus == TAILS
backflip++; //Add amount of tails
}
// A try to make an real exit out of a program
if ( choice == 2 )
{
EndProgram( frontflip, backflip, tosses );
}
System.out.println("\nChoose from the menu what you want to do.");
System.out.print("1. Toss the coin\n2. Quit program\n");
choice = input.nextInt();
}
}
//Toss the coin to determine 1 or 2.
public static int Flip()
{
int toss;
toss = 1 + randomNumbers.nextInt( 2 );
if ( toss == 1 )
{
System.out.println("You toss the coin and it lands on head!");
}
else
{
System.out.println("You toss the coin and it lands on tail!");
}
return toss;
}
public static void EndProgram( int frontflip, int backflip, int tosses )
{
System.out.printf("You have tossed %d times.\n", tosses);
System.out.printf("Of all those tosses, %d landed on heads, and %d on tails.\n", frontflip, backflip);
System.exit(0);
}
}
I think I need a do / while loop so that I can have the user answer the yes or no question of do you want to play again? and inside the loop I have a switch statement that also says if the user inputs 0 for the number of flips the program ends?
I thought I could add this snippet to get input:
System.out.println("How many flips do you want?");
System.out.println("(0 will exit the program)");
number = input.nextInt();
I was thinking of creating a new variable and have the user set the number of tosses. Then compound the while loop check like so
while(choice != 0 && numTosses !=0)
and then decrease the count and I'll have to check that count and once it reaches 0 print results as far as how many heads and how many tails then prompt the user if they would like to play the game again but I am having trouble getting the right. honestly I don't even know why I'm trying to do this if but for the knowledge aspect so if you don't wanna help a broski out I understand. I feel like I am on the right track.
You can use 2 loops:
public class CoinFlip {
private enum Coin {
HEADS,
TAILS
};
public static void main(String[] arguments) {
new CoinFlip();
}
CoinFlip() {
Scanner input = new Scanner(System.in);
int heads = 0, tails = 0;
while (true) {
System.out.println("How many flips do you want?");
System.out.println("(0 will exit the program)");
int number = input.nextInt();
if (number == 0)
break; // or System.exit
for (int i = 0; i < number; i++) {
Coin flipResult = flip();
switch (flipResult) {
case HEADS:
heads++;
break;
case TAILS:
tails++;
break;
}
}
System.out.println("Heads: " + heads);
System.out.println("Tails: " + tails);
}
}
private Coin flip() {
return Coin.values()[(int) (Math.random() * Coin.values().length)];
}
}
The while loop continues to ask the user to play again and again, if they put 0 your break it or exit it. In that loop, a for loop will iterate over the flips.
I am trying to create a die rolling program. The goal is to roll a die until the chosen value comes up a certain number of consecutive times (I used the programmer defined name "rollLength" for this). I am trying to display how many total rolls it took until the die value comes up consecutively. The problem is when I run the program it shows that the rollLength came up perfectly with no wasted rolls which I know is unrealistic. My question is if you can suggest what is wrong with my code. I am not sure if I am doing nested loops wrong.
Here is my code.
package lab03_schultz;
import java.util.Scanner;
import java.util.Random;
public class Lab03_Schultz {
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
//declare variables
int value, nSides, rollLength, roll;
int turns=0, n=0, count=0, totalThrows=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
while(n!=value) {
roll = randomNumber.nextInt(nSides)+1;
n++;
}
while(count!=rollLength){ //countinue till count = rollLength
if(n==value){
count++; //count how many times n == value, this is to represent consective rolls for the value
} else if (n!=value) { //if n is not the value counter starts over at zero
count=0;
}
if (n!=value) {//This will count how many times the die didn't come up with the value
totalThrows++;
}
}
System.out.println("totalThrows: " + totalThrows); //finding what totalThrows is
//adds rolls (without watched value) and (when it showed watch value) together
System.out.println("Your total throws are: " + (totalThrows+rollLength));
}
}
This can be done with just a single loop
int rollsInARow = 0; // store how many times we roll the value
int totalThrows = 0;
while(rollsInARow != rollLength) {
int roll = randomNumber.nextInt(nSides)+1;
if(roll == value) {
rollsInARow++; // Count consecutive rolls that are the wanted value
} else {
rollsInARow = 0; // Reset if we get a roll other than value
}
totalThrows++; // +1 after each roll
}
We loop until we have the wanted rollLength. Each loop generates a random number and compares it to value. If they are equal, increment the counter. If different, reset the counter. At the end of each loop, keep track of total rolls.
Also a tip. When using an if statement to check a true/false value (n == value), you can simply use an else statement to catch the n != value because there are only two cases.
if(n == value) {
count++;
} else { // The same functionality as else if(n != value)
count = 0;
}
Your first while loop will run until n is equal to the value. It will not move past that block of code until n is equal to value.