使用Main来管理骰子

时间:2014-10-30 04:41:03

标签: java

我应该编写一个简单的程序,在它们滚动100000次后读取两个骰子输入并将它们存储为直方图。但是,我使用一个类文件做了一切。我的导师希望我使用Main来管理Dice,但我只完成了骰子,但不知道如何将它集成到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;
    }
}

2 个答案:

答案 0 :(得分:1)

替换它:

//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]++;    
}

有了这个:

Dice d = new Dice();
for (int i = 0; i < rolls; i++) {
    d.roll();
    frequency[d.getTotal()]++;
}
但是,我不知道你实施一对骰子有多棒。我认为你可以从1到7滚动任何地方。另外,我不确定&#34; Bravo()&#34;函数应该是,你可以删除它。

答案 1 :(得分:0)

你需要这样的事情:

//Roll the dice
Dice myDice = new Dice();
for (int i=0; i<rolls; i++) {
    myDice.Bravo();
    die1 = myDice.getDie1();
    die2 = myDice.getDie2();
    total = myDice.getTotal();  
    frequency[total]++;    
}