Home > Blockchain >  for-loop controlling the number of times the Dice are rolled. (Java)
for-loop controlling the number of times the Dice are rolled. (Java)

Time:05-13

I am making a Java program to allow the user to input the number of times the dice are to be rolled. I am using a for loop with a timesRolled variable to control how many times to loop through the program. I want to add all of the random dice values to get the sum.

int timesRolled = 4;
int result = 0;

for (int i = 0; i < timesRolled; i  ) {
    int rand1 = getRandom(1,6); // getrandom is a function withing the template.
    result = rand1 ;
    outputln(result);
}

CodePudding user response:

You'll want to add the current value of result to the newly determined dice value in every iteration, and assign that to the result so: result = result rand1 or result = rand1 for short. Also calling the outputln(result); inside the for loop, will output the cumulative sum every iteration, so you might want to move it out the to output only once in the end.

int timesRolled = 4;
    int result = 0;

    for (int i = 0; i < timesRolled; i  ) {
        int rand1 = getRandom(1,6); // getrandom is a function withing the template.
        result  = rand1 ;
    }
outputln(result);
  • Related