0
我應該寫一個簡單的程序,讀取兩個骰子輸入後滾動100000次,並將它們存儲爲直方圖。但是,我利用一個類文件做了所有的事情。我的老師想讓我用Main來管理骰子,但我只完成了骰子,但不知道如何將它整合到主骰子中。使用主要管理骰子
我寫的程序:
public class Histogram {
public static void main(String[] args) {
int[] frequency = new int [13];
int die1, die2;
int rolls;
int asterisk;
int total;
double probability;
rolls = 100000;
//Roll the dice
for (int i=0; i<rolls; i++) {
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
total = die1 + die2;
frequency[total]++;
}
System.out.println("Results" + '\n' + "Each " + '\"' + "*" + '\"' + " represents the probability in one percent.");
System.out.println("The total number of rolls is one hundred thousand.");
System.out.println("Value\tFrequency\tProbability");
for (total=2; total<frequency.length; total++){
System.out.print(total + ": \t"+frequency[total]+"\t\t");
probability = (float) frequency[total]/rolls;
asterisk = (int) Math.round(probability * 100);
for (int i=0; i<asterisk; i++){
System.out.print("*");
}
System.out.println();
}
}
}
骰子:
public class Dice {
private int die1;
private int die2;
public Dice() {
roll();
}
public void roll() {
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
}
public int getDie1() {
return die1;
}
public int getDie2() {
return die2;
}
public int getTotal() {
return die1 + die2;
}
}