2014-11-21 55 views
-3

所以我找到了一種方法來打印最頻繁的值的頻率,當這對骰子滾動100000次。但是,我不會如何顯示最常見的值,而不是顯示它出現的次數。請幫忙。Java中最常見的值

目前的結果:
16716(這是最常見的價值上來的次數,但不是最常見的值。)
結果:
平均值爲6.98691。
標準差是4.70269534109257。
每個「」代表百分之一。
卷的總數是十萬。
指數值百分比
2:2815

3:5603 ******
4:8307 ********
5:11148 ********* **
6:14031 **************
7:16716 *****************
8:13821 ** ************
9:11071 ***********
10:8289 ********
11:5399 **** *
12:2800 *

主類:

public class Alpha { 

public static void main(String[] args) { 

    Histogram(); 
} 

public static void Histogram() { 

    int rolls = 0; 
    int[] getFrequency = new int [13]; //Declares the array 
    int total; 
    int scale; 
    int maxValue = 0; 
    double frequency; 
    double average; 
    double Average; 
    double stdev; 
    double getTotal = 0; 
    double sum = 0; 
    Bravo dice; 
    dice = new Bravo();; 

    rolls = 100000; 

    //Roll the dice 
    for (int i=0; i<rolls; i++) { 
     dice.roll(); 
     getFrequency[dice.getTotal()]++; 
     sum += dice.getTotal(); 
     average = sum/rolls; 
     getTotal += Math.pow((dice.getTotal()-average),2); 
    } 

    for (total = 2; total < getFrequency.length; total++) { 
     if (getFrequency[total] > maxValue) { 
      maxValue = (int) getFrequency[total]; 
     } 
     else { 

     } 
    } 
    System.out.println(maxValue); 

    average = sum/rolls; 
    Average = getTotal/rolls; 
    stdev = Math.sqrt(Average); 

    System.out.println("Results:" + "\n" + 
    "The average is " + average + "." + "\n" + 
    "The standard deviation is " + stdev + "." + "\n"+ 
    "Each " + '\"' + "*" + '\"' + " represents one percent."); 
    System.out.println("The total number of rolls is one hundred thousand."); 
    System.out.println("Index\tValue\tPercent"); 

    //output dice rolls 
    for (total=2; total<getFrequency.length; total++){ 
     System.out.print(total + ": \t"+getFrequency[total]+"\t"); 
     frequency = (double) getFrequency[total]/rolls; 
     scale = (int) Math.round(frequency * 100); 

     for (int i=0; i<scale; i++){ 
      System.out.print("*"); 
     } 
     System.out.println(); 
    } 
} 

}

輔助類別:

public class Bravo { 
private int die1; 
    private int die2; 
    public Bravo() { 
     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

稍微修改for循環:

int modeValue=2; 
for (total = 2; total < getFrequency.length; total++) { 
    if (getFrequency[total] > maxValue) { 
     maxValue = (int) getFrequency[total]; 
     modeValue = total; 
    } 
    else { 

    } 
} 
System.out.println("Most common value is" + modeValue);