使用Main管理骰子

  • 本文关键字:管理 Main 使用 java
  • 更新时间 :
  • 英文 :


我应该写一个简单的程序,在两个骰子被掷100000次后读取它们,并将它们存储为直方图。然而,我利用一个类文件完成了所有工作。我的教练希望我使用Main来管理骰子,但我只完成了骰子,但不知道如何将其集成到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("ValuetFrequencytProbability");
    for (total=2; total<frequency.length; total++){ 
        System.out.print(total + ": t"+frequency[total]+"tt");
        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;
    }
}

替换此:

//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的任何地方滚动。此外,我不确定"Bravo()"函数应该是什么,你可能会删除它。

您需要这样的东西:

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

最新更新