如何确保数组包含某些值



我是编码新手,我想知道如何确保特定数组包含某些值?

这就是我所拥有的,但对我来说不起作用。我曾尝试在互联网上寻找解决方案,但我被很多问题弄糊涂了。任何反馈都有帮助!

public static boolean allnumbers(int[] arr) {// makes sure only numbers 1-9 are used
boolean[] found = new boolean[9]; // creates a boolean array 
for (int row = 0; row > 1 && row > 9; row++) {
int index = arr[row] - 1;
if(!found[index]) {
found[index] = true;
} else{
return false; //returns false if there are numbers that are not between 1-9
}
}
return true;
}
/**
* Checks if this array consists of numbers 1 to 9, with all unique numbers,
* and no number missing.
*
* @param arr input array
* @return true if this array has numbers 1 to 9, each occurring exactly once
*/
public static boolean allnumbers(int[] arr) {
if (arr.length != 9) return false;
return IntStream.rangeClosed(1, 9)
.noneMatch(value -> Arrays.stream(arr).noneMatch(a -> a == value));
}

另一种方式。。。

public static boolean allnumbers(int[] arr) {
return Arrays.stream(arr).boxed().collect(Collectors.toSet())
.equals(IntStream.rangeClosed(1, 9).boxed().collect(Collectors.toSet()));
}

或者,如果你只想检查没有数字在1-9范围之外的事实,你可以使用这个:-

public static boolean allnumbers(int[] arr) {
return Arrays.stream(arr)
.noneMatch(i -> i < 1 || i > 9);
}

这是您的问题的解决方案:

public static boolean allnumbers(int[] arr) {// makes sure only numbers 1-9 are used
for(int row=0; row < 9; row++){
if (arr[row] < 1 || arr[row] > 9)
return false;
}
return true;
}

如果且仅当且仅当arr中的前9个元素在1和9之间(包括1和9(,则此函数将返回true。

最新更新