Java 如何检查数组中的所有值是否都高于特定数量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19737105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if all values in an array are higher than a specific amount?
提问by Robert
OK so in this program I'm making I have to check if allof the values in the Array are greater than a specific number.
好的,所以在这个程序中,我必须检查数组中的所有值是否都大于特定数字。
this is what i have so far
这是我迄今为止所拥有的
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;
}
the limit variable is the number that all the number in the array have to be grater or qual to.
limit 变量是数组中所有数字必须大于或等于的数字。
Can you help me fix this and explain why my way doesn't work?
你能帮我解决这个问题并解释为什么我的方法不起作用吗?
采纳答案by Prateek
Instead of checking if all elements are greater than a specific number just check if one number is less than the specific number and return false
if there is one else return true
与其检查所有元素是否都大于特定数字,只需检查一个数字是否小于特定数字以及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;
}
回答by Terry Chern
Unless you are passing in the value for the limit as well as the array you're checking, the method won't work. Change your header to something like:
除非您传入限制的值以及您正在检查的数组,否则该方法将不起作用。将您的标题更改为:
public static boolean isGameover(int limit, int[] data)
This should be enough to get your code working (your parameters aren't set up properly). I offer you an alternate solution with less steps involved.
这应该足以让您的代码工作(您的参数设置不正确)。我为您提供了一种替代解决方案,涉及的步骤较少。
You need to find out if allof the numbers in the array are greater than the limit, so the only condition you need to check is if anyof the elements of the array are less than the limit.
您需要找出数组中的所有数字是否都大于限制,因此您需要检查的唯一条件是数组中的任何元素是否小于限制。
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.