如何检查数组中的所有值是否高于特定数量?

时间:2013-11-01 23:32:07

标签: java arrays

好的,所以在这个程序中,我必须检查数组中 所有 的值是否大于特定数字。

这是我到目前为止所拥有的

public static boolean isGameOver(){
  int check = 0;
  for(int k = 0; k < data.length; k++){
    if (data[k] >= limit)
      check++;
  }
  if (check == data.length)
    return true;
  else 
    return false;
}

limit变量是数组中所有数字必须是grater或qual to的数字。

你能帮助我解决这个问题并解释为什么我的方式不起作用吗?

3 个答案:

答案 0 :(得分:4)

不检查所有元素是否大于特定数字,只需检查一个数字是否小于特定数字,如果还有其他数字return false,则检查return true

public static boolean isGameOver(int limit, int[] data){
      for(int k = 0; k < data.length; k++){
        if (data[k] < limit)
          return false;
      }
      return true;
    }

答案 1 :(得分:1)

除非您传入限制值以及要检查的数组,否则该方法将不起作用。将标题更改为:

public static boolean isGameover(int limit, int[] data)

这应该足以使您的代码正常工作(您的参数设置不正确)。我为您提供了一个替代解决方案,其中涉及的步骤更少。

您需要查明数组中所有数字是否大于限制,因此您需要检查的唯一条件是任何元素数组的数量小于限制。

for(int i = 0; i < data.length; i++){
    if(data[i] <= limit) // the condition you're checking for is that they're all greater than, so if its less than or equal to, it gets flagged
        return false;
}
return true; // if it goes through the whole array without triggering a false, it has to be true.

答案 2 :(得分:1)

您可以使用ES 6新功能(称为每种方法和箭头功能

)轻松完成
var bAges= [11, 22, 4, 5, 6, 7, 8, 99];

var gAges= [11, 22, 43, 45, 16, 71, 88, 99];

var ageLimit = 10 ;

 bAges.every(x => x >= ageLimit ); //  false

gAges.every(x => x >= ageLimit ); // true

<强>解释

每个方法检查所有数组项是大于等于10,如果所有数组项都大于或等于那么它将返回true否则它将返回false。 在Es 6中有另一个方法叫做some会检查所有项目,如果一个项目符合条件,那么它将返回true,否则它将返回false

 bAges.some(x => x >= ageLimit ); //  ture

[2, 3, 4, 5, 6 ].some(x => x >= ageLimit ); // false
相关问题