Java - 检查给定索引处的数组是否包含给定的int

时间:2014-10-05 13:34:58

标签: java arrays int

我有一个数组,可以计算在骰子模拟器中出现1到6的每个值的次数,这个模拟器会掷骰子" 100次。我的目标是找到最常见的骰子。

到目前为止这是我的代码,除了最后只输出" 6"的for-loop之外,一切正常。

    Random dice = new Random();

    int diceThrow[] = new int[100];
    int throwsPerDice[] = new int[6];       

    for(int i = 0; i < 100; i++){
        diceThrow[i] = dice.nextInt(6) + 1;

        switch (diceThrow[i]){
            case 1:
                throwsPerDice[0]++;
                break;
            case 2:
                throwsPerDice[1]++;
                break;
            case 3:
                throwsPerDice[2]++;
                break;
            case 4:
                throwsPerDice[3]++;
                break;
            case 5:
                throwsPerDice[4]++;
                break;
            case 6:
                throwsPerDice[5]++;
                break;
            default:
                System.out.println("error");
        }

    }

    Arrays.sort(throwsPerDice);
    int max = throwsPerDice[throwsPerDice.length-1];
    int mostFrequent = 0;

    //Only outputs "mostFrequent = 6;" Why?
    for(int i = 0; i < throwsPerDice.length; i++){
        if(max == throwsPerDice[i]){
            mostFrequent = i+1;
        }
    }

    System.out.println("Most frequent dice roll : " + mostFrequent);

对我做错了什么的任何想法?我试图让代码简短易行。我在第一学期学习java,所以一个不成熟的解决方案会更好。

另外,是否可以在不使用switch / if语句的情况下计算每个diceThrow的频率?

3 个答案:

答案 0 :(得分:1)

主要问题是,一旦你排序throwsPerDice,就不再知道哪个计数指的是哪个死亡。无论你以后做什么,你都无法恢复这些信息。

您的代码始终返回6,因为最高分数已被分类到throwsPerDice中的最终位置。

答案 1 :(得分:0)

让我们说你的数组包含

 [10, 20, 30, 20, 5, 15]

在第一次循环之后。

现在代码对数组进行排序,因此它变为

[5, 10, 15, 20, 20, 30]

max初始化为数组中的最后一个值:30。

现在最后一个循环迭代以找到包含max元素的数组的索引。当然,它总是最后一个,因为你只是对数组进行了排序。

重新思考你的算法:不要对数组进行排序,而是迭代数组以找到最大元素及其索引。

请注意:您的big switch语句应替换为

throwsPerDice[diceThrow[i] - 1]++;

答案 2 :(得分:0)

删除这部分代码:

Arrays.sort(throwsPerDice);
int max = throwsPerDice[throwsPerDice.length-1];
int mostFrequent = 0;

//Only outputs "mostFrequent = 6;" Why?
for(int i = 0; i < throwsPerDice.length; i++){
    if(max == throwsPerDice[i]){
        mostFrequent = i+1;
    }
}

并替换它:

int mostFrequent = 0;
for(int i = 0; i < throwsPerDice.length; i++){
    if(throwsPerDice[i] > throwsPerDice[mostFrequent]){
        mostFrequent = i;
    }
}
System.out.println("Most frequent dice roll : " + mostFrequent + 1);

这会奏效。您的代码无效,因为您在使用时未跟踪骰子:Arrays.sort