I'm doing the following problem: Write a Java program to find the index of a value in a sorted array. If the value does not find return the index where it would be if it were inserted in order.
My issue here is when I add a value (not already within the list - and after sorting it), I don't get the index of this value. It keeps returning me -1, I do not understand why? what is wrong? Or what am I missing? Any explanations? Help? Thank you
Here is my code :
import java.util.*; public class indexSortedArray { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { // init array and linked list of array nums Integer[] nums = { 1, 2, 4, 5, 6 }; List<Integer> list = Arrays.asList(nums); java.util.LinkedList<Integer> linkedList = new java.util.LinkedList<Integer>(list); // get user input value System.out.print("Value you are looking for? "); int value = input.nextInt(); // if value not member of list, add value and sort the list if (isMemberLinkedList(linkedList, value) == false) { linkedList.add(value); Collections.sort(linkedList); } System.out.println("LinkedList of above array " + linkedList); // print linked list // get value index and print it int getIndex = Arrays.asList(nums).indexOf(value); System.out.println(value + " is located at " + getIndex + " index"); // -1 if not inside the list } } // check if value inside linked list static boolean isMemberLinkedList(List<?> list, int val) { boolean check = false; Iterator<Integer> it = (Iterator<Integer>) list.iterator(); // to iterate through the linked list // browse linked list while (it.hasNext()) { if (it.next() == val) { check = true; // System.out.println("change made"); } } return check; } }