我正在做一个掷骰子项目,有点卡住了。我仍然对Java编程和使用数组还不熟悉,所以我确定自己搞砸了。最终目标是输出一张包含掷骰数(我拥有且有效)的表格,然后根据掷骰数将骰子掷骰总数相加。该表有效,但是我很难获取总和。如果我掷出4个骰子,我仍然得到1-3的总和。有人可以带我一起工作吗?我被卡住了! ):
import javax.swing.*;
import java.util.Random;
public class Lab1 {
private static int N = 0;
private static int M = 0;
private static int total = 0;
private static Random rnd = new Random();
private final static int FACENUMBER = 6;
private static int faceValue = 1;
public Lab1() {
}
public static void main(String[] args) {
N = Integer.parseInt(JOptionPane.showInputDialog("How many dice would you like to roll?"));
System.out.println("Dice: " + N);
M = Integer.parseInt(JOptionPane.showInputDialog("How many times would you like to roll?"));
System.out.println("Rolls: " + M);
System.out.println();
int total[] = new int[(M) + 1];
for (int roll = 1; roll <= M; roll++) {
total[roll] = rnd.nextInt(FACENUMBER * N) + 1;
}
System.out.printf("%3s%12s\n", "Rolls", " Sum of Rolls");
for (int k = 1; k < total.length; k++) {
System.out.printf("%3s%12s\n", k, total[k]);
}
}
}
最佳答案
使用:
rnd.nextInt(FACENUMBER*N)+1;
您在
1
和(FACENUMBER*N)+1
之间得到一个随机数如果用户为N输入10,则实际上需要在
1
和61
之间的数字时,每个滚动都会得到10
和60
之间的数字。您想要的是:
rnd.nextInt((FACENUMBER-1)*N)+N
不过,这不是模拟骰子的正确方法。考虑到只有一种方法可以得出60,但有很多方法可以得出类似30的其他总数。以下解决方案更好:
for(int roll=0; roll<N; roll++) {
total[roll] = rnd.nextInt(FACENUMBER)+1
}