import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class WordList {

	String[] words;

	//reads in strings from file filename into words
	private void readStrings(String filename) {
		File file = new File(filename);

		Scanner reader;
		try{
			reader = new Scanner(file);
		} catch (FileNotFoundException excep) {
			System.err.println("Error: file not found");
			System.exit(1);
			reader = new Scanner(""); //should not get here
		}
		int index = 0;

		while (reader.hasNextLine()) {
			if(index >= words.length) {
				System.err.println("Error: number of lines too small");
				System.exit(1);
			}
			words[index] = reader.nextLine();
			index++;
		}

		reader.close();
	}

	//returns true if target is in the list of words;
	//false otherwise  
	public boolean isInList(String target) {
		int left = 0;
		int right = words.length - 1;

		while (left <= right) {
			int mid = left + (right - left) / 2;

			int comparison = target.compareTo(words[mid]);

			if (comparison == 0) {
				return true;  // Found
			} else if (comparison < 0) {
				right = mid - 1;  // Search left half
			} else {
				left = mid + 1;   // Search right half
			}
		}

		return false;  // Not found
	}

	//reads in file named filename, stores in the list of words
	//numWords must be the number of lines in filename
	public WordList(int numWords, String filename) {
		words = new String[numWords];
		readStrings(filename);
	}

	public static void main(String[] args) {
		//example: English.txt stores stores all English words
		WordList dict = new WordList(279456, "english.txt");
		System.out.println(dict.isInList("TEST"));
	}
}
