英文:
Check if an int[] array is in range using if statements in Java
问题
以下是翻译好的部分:
我的代码如下所示:
public Goals(int[] points){
this.points = points;
}
然后我需要检查数组是否在范围内:
public int getpoints() {
if (points <= 0 && >= 10) {
//做一些操作
}
}
但是它不允许我在数组中使用运算符。
我应该如何处理?
英文:
My code looks like this:
public Goals(int[] points){
this.points = points;
}
then I'll have to check if the array is within the range:
public int getpoints() {
if (points <= 0 && >= 10) {
//do something
}
}
but it doesn't allow me to use operators with arrays.
How should I do this?
答案1
得分: 1
如果我理解正确,它会起作用:
private static boolean isWithinRange(int[] points, int minRange, int maxRange) {
boolean outOfRange = Arrays.stream(points).anyMatch( p -> p < minRange || p > maxRange );
return !outOfRange;
}
英文:
If I got it right, it would do the trick:
private static boolean isWithinRange(int[] points, int minRange, int maxRange) {
boolean outOfRange = Arrays.stream(points).anyMatch( p -> p < minRange || p > maxRange );
return ! outOfRange;
}
答案2
得分: 0
我不太了解你的问题,但如果你正在寻找一种检查点数组中所有元素是否在范围内的方法,请参考以下内容:
boolean isInRange = Arrays.stream(points).allMatch(point -> [每个元素的条件]);
英文:
I don't really know your question, but if you looking for a way to check if all of element in points array is in range, check this
boolean isInRange = Arrays.stream(points).allMatch(point -> [Your condition for each element]);
答案3
得分: 0
如果您想检查点是否在0到10的范围内,您可以使用类似以下的代码:
public class InRange {
public static void main(String[] args){
checkRange();
}
private static void checkRange() {
int[] points = new int[3];
points[0] = -1;
points[1] = 6;
points[2] = 11;
for(int i = 0; i<points.length; i++){
if(points[i] >= 0 && points[i]<=10){
System.out.println(points[i] + " 点在0到10之间");
}else{
System.out.println(points[i] + " 点不在0到10之间");
}
}
}
}
英文:
If you trying to check if points are within the range of 0 and 10, you could use something like
public class InRange {
public static void main(String[] args){
checkRange();
}
private static void checkRange() {
int[] points = new int[3];
points[0] = -1;
points[1] = 6;
points[2] = 11;
for(int i = 0; i<points.length; i++){
if(points[i] >= 0 && points[i]<=10){
System.out.println(points[i] + " Point between 0 and 10");
}else{
System.out.println(points[i] + " Point not Between 0 and 10");
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论