2014-10-30 16 views
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; 
    } 
} 

回答

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的任何位置滾動。另外我不確定「Bravo()」功能應該是什麼,你可以刪除它。

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