所以我需要创建一个直方图,显示4个骰子的总和的结果。该程序每次滚动时都会获取骰子的总数。我需要在骰子滚动循环中创建每个数字频率的直方图。这是我的代码:
import java.util.Scanner;
import java.util.Random;
import java.util.Scanner;
import java.lang.Math;
public class DieSimulator
{
public static void main(String[] args)
{
Die d1 = new Die(6);
Die d2 = new Die(6);
Die d3 = new Die(6);
Die d4 = new Die(6);
int roll = 100;
int [] rolls = new int[roll];
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;
int ten = 0;
int eleven = 0;
int twelve = 0;
int thirteen = 0;
int fourteen = 0;
int fifteen = 0;
int sixteen = 0;
int seventeen = 0;
int eighteen = 0;
int nineteen = 0;
int twenty = 0;
int twentyone = 0;
int twentytwo = 0;
int twentythree = 0;
int twentyfour = 0;
for (int i=0; i < rolls.length; i++)
{
int n1 = d1.cast();
//System.out.print(n1 + "");
int n2 = d2.cast();
//System.out.print(n2 + "");
int n3 = d3.cast();
//System.out.print(n3 + "");
int n4 = d4.cast();
int sum = n1 + n2 + n3 + n4;
if (sum == 4)
four++;
if (sum == 5)
five++;
if (sum == 6)
six++;
if (sum == 7)
seven++;
if (sum == 8)
eight++;
if (sum == 9)
nine++;
if (sum == 10)
ten++;
if (sum == 11)
eleven++;
if (sum == 12)
twelve++;
if (sum == 13)
thirteen++;
if (sum == 14)
fourteen++;
if (sum == 15)
fifteen++;
if (sum == 16)
sixteen++;
if (sum == 17)
seventeen++;
if (sum == 18)
eighteen++;
if (sum == 19)
nineteen++;
if (sum == 20)
twenty++;
if (sum == 21)
twentyone++;
if (sum == 22)
twentytwo++;
if (sum == 23)
twentythree++;
if (sum == 24)
twentyfour++;
System.out.println("Total Dice roll: " + sum);
System.out.println(twenty);
}
int[] histogram = new int[20];
System.out.print(histogram);
}
}
我用什么代码来创建直方图?
答案 0 :(得分:0)
更改为这样的数组。可以使用SparseArray,因为索引0,1,2,3从未使用过,但对我来说似乎不值得。我使数组25长(24 + 1),因此结果[x]保持x的骰子滚动发生的次数。
import java.util.Scanner;
import java.util.Random;
import java.util.Scanner;
import java.lang.Math;
public class DieSimulator
{
public static void main(String[] args)
{
Die d1 = new Die(6);
Die d2 = new Die(6);
Die d3 = new Die(6);
Die d4 = new Die(6);
int roll = 100;
int [] rolls = new int[roll];
int [] results = new int[25];
for (int i=0; i < rolls.length; i++)
{
int n1 = d1.cast();
//System.out.print(n1 + "");
int n2 = d2.cast();
//System.out.print(n2 + "");
int n3 = d3.cast();
//System.out.print(n3 + "");
int n4 = d4.cast();
int sum = n1 + n2 + n3 + n4;
results[sum]++;
System.out.println("Total Dice roll: " + sum);
}
System.out.print(results);
}
}
答案 1 :(得分:0)
补充RobP的答案,要获得直方图,请在主要功能结束前添加:
for(int i = 4; i < 24; i++) {
System.out.println("Result: " + i + " has got " + results[i] + " hit(s)");
}
我还注意到您没有访问rolls
数组。您只需使用其大小来限制您的迭代次数。
for (int i = 0; i < 100; i++)
会做同样的事情......而不是在内存中分配数组。