(Newbie Wang) In making JAVA dice,

Asked 2 years ago, Updated 2 years ago, 19 views

How to roll 2 dice randomly and find the sum of the values To find the sum of the values by rolling them an additional n times I'm trying to solve it, but I can't do it without web surfingㅜㅜ It would be most efficient to use a while sentence, right??

java

2022-09-21 15:47

1 Answers

Do your homework yourself and ask questions if you are not sure.

From Java 8 and above, you can write it as if you are using a functional language.

The code below is the code that randomly generates 10 of the numbers between 1 and 6 and adds them all. Since there are two dice, I added two sum results.

jshell> import java.util.Random;

jshell> Random r = new Random();
r ==> java.util.Random@14acaea5

jshell> r.ints(1, 7).limit(10).sum() + r.ints(1, 7).limit(10).sum()
$3 ==> 81

jshell> r.ints(1, 7).limit(10).sum() + r.ints(1, 7).limit(10).sum()
$4 ==> 62

jshell> r.ints(1, 7).limit(10).sum() + r.ints(1, 7).limit(10).sum()
$5 ==> 72

jshell> r.ints(1, 7).limit(10).toArray()
$6 ==> int[10] { 1, 2, 6, 1, 6, 6, 5, 3, 4, 1 }

If it's like throwing two dice at the same time....

The code below is repeated 10 times by obtaining two numbers at the same time and adding them.

jshell> import java.util.Random;
jshell> import java.util.stream.IntStream;
jshell> r.ints(1, 7).parallel().limit(2).toArray()
$21 ==> int[2] { 5, 5 }

jshell> int totalSum = 0;
jshell> IntStream.rangeClosed(1, 10).forEach(i->totalSum += r.ints(1, 7).parallel().limit(2).sum())
jshell> totalSum
totalSum ==> 76


2022-09-21 15:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.