Hello I am building a Java program that takes in a file called wordlist which contains all of the words in the dictionary, one per line, and I pass it in through a scanner so that later I can use algorithms to search through it:
File file = new File("wordlist.txt");
Scanner scanner = new Scanner(file);
String [] words = new String[69903];
No problem here. Then I try to populate the words array using a for loop:
for(int i = 0; scanner.hasNextLine(); i++) {
String input = scanner.nextLine();
words[i] = input;
}
This is where the problem is. I tried printing input every iteration of the loop and its an actual word from the .txt file. I also tried printing words[i] during the loop for each iteration and it also worked. Yet somehow when I iterate through the array after the loop it is full of nulls which obviously creates problems for the program down the line. What is happening and how can I fix it. Thank you.
By the way here is the entire program:
import java.util.Scanner;
import java.util.Arrays;
import java.io.File;
public class BinarySearch {
public static void main(String[] args) throws Exception {
File file = new File("wordlist.txt");
Scanner scanner = new Scanner(file);
String [] words = new String[69903];
// Something here not working
for(int i = 0; scanner.hasNextLine(); i++) {
String input = scanner.nextLine();
words[i] = input;
}
System.out.println("Done reading input words");
System.out.println("Done sorting input words");
Scanner query = new Scanner(System.in);
String key = query.nextLine();
if(search(key, words, 0, words.length) < 0) {
System.out.println(key + " is not in the english dictionary.");
} else {
System.out.println(key + " is part of the english dictionary.");
}
}
public static int search(String key, String[] arr, int lo, int
hi) {
if(hi <= lo) {
return -1;
}
int mid = lo + (hi - lo) / 2;
int compute = arr[mid].compareTo(key);
if (compute > 0) {
return search(key, arr, lo, mid);
}
if (compute < 0) {
return search(key, arr, mid + 1, hi);
}
else {
return mid;
}
}
}
This is the error I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 69903 at BinarySearch.main(BinarySearch.java:19)