2014-10-05 73 views
0

我有一个数组,用于计算从1到6的每个值出现在掷骰子100次的骰子模拟器中的次数。我的目标是找到最频繁的掷骰子。Java - 检查给定索引处的数组是否包含给定的int

这是我的代码到目前为止,除了最后只输出“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,所以一个不太先进的解决方案会更好。

此外,是否有可能计算每个diceThrow的频率而不使用开关/ if语句?

+2

你知道,那个switch语句是完全没有必要的。 – 2014-10-05 13:58:17

回答

0

比方说,你的数组包含

[10, 20, 30, 20, 5, 15] 
第一循环之后

现在代码排序的数组,所以它成为

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

而且max与数组中的最后一个值初始化:30

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

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

只是注意:你的大switch语句应该

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

谢谢!我现在正在工作:-) – Ferdinand 2014-10-05 14:33:19

1

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

您的代码总是返回6,因为最高的计数已排序到throwsPerDice的最终位置。

+0

啊,我明白了!我没有注意到这一点。谢谢! – Ferdinand 2014-10-05 14:26:56

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

相关问题