Java中最常见的价值

时间:2014-11-21 05:47:29

标签: java

所以我找到了一种方法来打印最频繁的值的频率,以便当这对骰子滚动100000次时。但是,我不知道如何显示最常见的值而不是它出现的次数。请帮忙。

目前的结果:
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 个答案:

答案 0 :(得分: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);
相关问题