2014-11-21 56 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);