Home>

### java game creation i would like to know how to calculate the total value of random numbers

It's been a month and a half since I started studying Java, and I have the task of creating a simple game.
The contents of the game are as follows.
・ 3 players
・ Roll the dice 3 times each and find the total value for each.
・ The person with the largest total value wins

I'm creating it using an array and random numbers, but I'm stumbling because I don't know how to write the code to find the total value.
I would appreciate it if you could teach me.
I look forward to working with you.

[1]: 5 3 1
9 ← The total value is not calculated, and it seems that the random number is output as it is.
[2]: 2 6 3
8 ← The total value is not calculated, and it seems that the random number is output as it is.
[3]: 5 2 6
5 ← The total value is not calculated, and it seems that the random number is output as it is.

Corresponding source code

package test;

public class SaikoroGames {

public static void main (String [] args) {

// Decide the number of players
int [] r = {1,2,3};

int sum = 0;

// Loop for the number of people
for (int j = 0;j System.out.print ("[" + r [j] + "]" + ":");
for (int i = 0;i for (int n = 0;n<1;n ++) {
System.out.print (dice () + "");
sum = dice () + dice () + dice ();
}
}
System.out.println ();
System.out.print (sum);
System.out.println ();
}
}

// roll the dice
static int dice () {
return (int) (Math.random () * 6) + 1;
}
}

What I tried

I googled how to find the total value using an array and random numbers, but it didn't work.

Supplementary information (FW/tool version, etc.)

The cause is here

``````for (int i = 0;i<r.length;i ++) {
for (int n = 0;n<1;n ++) {
// Here, a random number is generated and displayed.
System.out.print (dice () + "");
// I am trying to make a total value here, but it is not the number displayed above because it has nothing to do with the random number above
sum = dice () + dice () + dice ();
}
}``````

The dice function only describes the process of randomly creating numbers.
So the dice () displayed in print and the dice () performed in sum areIt's a different thing
If you tell me completely, it will not be good for you, so I commented on the pointed out part.

-Let's define a variable once and put it in it instead of displaying dice () directly. Then you can use it for other processing without losing the numerical value.

``````int hokan = 0;
hokan = dice ();``````

・ How about calculating the total value every time you ask for a random number?

``sum + = ○○``

Something is entered in ○○. It is the same as the one displayed by print, so you should be able to do it by referring to the first hint.
However, in the total calculation and output respectively`dice ()`Is called, so the displayed value is not used for the total.