very new to java and oop in general. so be kind.
I have one text file which contains 10 integers, searchkeysArray.txt. The program creates an array named keysArr. I have another text file of 500 random integers, array1.txt. The program creates another array named array1.
I want to use the linearSearch method I created to search for the elements of keysArr within array1 and output the index which it exist.
public static int linearSearch(int arr[], int x) { int size = arr.length; for(int i = 0; i < size; i++) { if(arr[i] == x) return i; } return -1; } readFile method
public static int[] readFile(String file) { try { File f = new File(file); Scanner s = new Scanner(f); int ctr = 0; while (s.hasNextInt()) { ctr++; s.nextInt(); } int[] arr = new int[ctr]; //create array of that size Scanner scanner2 = new Scanner(f); for (int i = 0; i < arr.length; i++) arr[i] = scanner2.nextInt(); return arr; } catch(Exception e) { return null; } the program.
public static void main(String[] args) { int[] keysArr = readFile("searchkeysArray"); int[] array1 = readFile("array17"); int key = 34; int result = linearSearch(array1, key); if (result != -1) System.out.print("The element " +key+" is present in the array, at index " + result + " "); else System.out.print("The element " +key+" is not present in the array "); } and it outputs
The element 34 is present in the array, at index 359 which makes sense. I've manually tested numbers and (apparently) everything works fine. But I do not quite understand how I'm supposed to use keysArr as my key rather than int x = some number.
Want to output something like
The element [keysArr[0]] is present in the array, at index 359 The element [keysArr[1]] is present in the array, at index 547 ... The element [keysArr[4]] is not present in the array and so on. Right now keysArr just an array of 10 integers but I will eventually use hundreds..