[英]Finding if given Integer is in Array or not using Arraylist contains ()
Having problem to check if the given input is in Array or not. 检查给定输入是否在数组中时遇到问题。 Below is just the sample code I wrote.
下面只是我编写的示例代码。 For some reason no matter what I input it outputs "not Okay" even if the number is in array.
由于某种原因,无论我输入了什么,即使数字在数组中,它也会输出“ not Okay”。 Any Suggestion or help will be appreciated.
任何建议或帮助将不胜感激。
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int array [] = new int[10];
System.out.println("Please enter the 10 positive integers for BST:");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
System.out.println("Enter node to delete");
if (Arrays.asList(array).contains(input.nextInt())){
System.out.println("ok");
} else
System.out.println("not Okay");
}
Arrays.asList(array)
will convert the int[] array
into a List<int[]>
, then List<int[]>#contains
will try to search an Integer
. Arrays.asList(array)
将int[] array
转换为List<int[]>
,然后List<int[]>#contains
将尝试搜索Integer
。 As noted, it will never find it. 如前所述,它将永远找不到。
Ways to solve this: 解决方法:
Change int[]
to Integer[]
. 将
int[]
更改为Integer[]
。
Create a method that receives an int
and search the element in the array. 创建一个接收
int
的方法并搜索数组中的元素。
(Code won't be shown in the answer since the question looks like a homework exercise). (由于问题看起来像是一项家庭作业,因此答案中不会显示代码)。
You can use Arrays.binarySearch()
. 您可以使用
Arrays.binarySearch()
。 It returns the index of the key, if it is contained in the array; 如果键的索引包含在数组中,则返回键的索引。 otherwise, (-(insertion point) - 1).
否则为(-(插入点)-1)。 You must use
sort()
method before: 您必须先使用
sort()
方法:
Arrays.sort(array);
if (Arrays.binarySearch(array, input.nextInt()>=0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.