Reputation: 105
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. 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");
}
Upvotes: 0
Views: 61
Reputation: 31
You can use Arrays.binarySearch()
. It returns the index of the key, if it is contained in the array; otherwise, (-(insertion point) - 1). You must use sort()
method before:
Arrays.sort(array);
if (Arrays.binarySearch(array, input.nextInt()>=0)
Upvotes: 2
Reputation: 85779
Arrays.asList(array)
will convert the int[] array
into a List<int[]>
, then List<int[]>#contains
will try to search an Integer
. As noted, it will never find it.
Ways to solve this:
Change int[]
to Integer[]
.
Create a method that receives an int
and search the element in the array.
(Code won't be shown in the answer since the question looks like a homework exercise).
Upvotes: 2