0

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");
}
0

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir. Worked just fine
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.