So my program is functional. I just want it to use a binary search of a text file and determine the highest index number it can be found in. If it cannot be found it finds the next largest and makes it a negative. My problem is right now the array size that gets made is 11. That is because it is how many integers are in the text file I am using. What if I will not know the number of integers? I understand people suggest making a list but will that not accept repetitions? why does this section of code:
while(scanner.hasNextInt()){
arr[i++] = scanner.nextInt();}
scanner.close();
not change my array size as necessary?
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class BinarySearch {
public static int binarysearch(int[] arr, int key)
{
int lo = 0, hi = arr.length - 1;
{
while (lo < hi)
{
int mid = (lo + hi) / 2;
if (arr[mid] <= key)
lo = mid + 1;
if (arr[mid] > key)
hi = mid;
}
if (arr[lo] == key) {
return lo;
}
else if ((arr[lo] != key) && (arr[lo-1] == key)){
return lo - 1;
}
else{
return (binarysearch( arr,(key-1))* - 1);
}
}
}
public static void main(String[] args) throws IOException{ {
int k = Integer.parseInt(args[1]);
Scanner scanner = new Scanner(new File(args[0]));
int[] arr = new int[11];
int i = 0;
while(scanner.hasNextInt()){
arr[i++] = scanner.nextInt();}
scanner.close();
System.out.println(binarysearch(arr, k));
}}
}