// Arup Guha
// 4/9/2026
// Example Program to illustrate reading from a file
// and Java's built in binary search.

import java.util.*;
import java.io.*;

public class WordSearch {

	public static void main(String[] args) {
	
		Scanner stdin = new Scanner(System.in);
		System.out.println("Please enter your dictionary file.");
		String filename = stdin.next();
		Scanner fin = null;
		
		// So we get a valid file.
		while (true) {
		
			// Try opening the file.
			try {
				fin = new Scanner(new File(filename));
			}
			catch (FileNotFoundException e) {
				System.out.println("Sorry, that file wasn't found. Try again.");
				filename = stdin.next();
			}
			
			// We're good.
			if (fin != null) break;
		}
		
		// Read from the file, get all the words.
		int numWords = fin.nextInt();
		String[] words = new String[numWords];
		for (int i=0; i<numWords; i++)
			words[i] = fin.next();
			
		// Close the file.
		fin.close();
		
		System.out.println("Do you want to enter a word to search for?");
		String response = stdin.next().toLowerCase();
		
		// Go as long as the user wants to search for words.
		while (response.charAt(0) == 'y') {
		
			// Get next word.
			System.out.println("What word do you want to search for?");
			String word = stdin.next();
			
			// Finds the index where word is, or returns a negative integer
			// indicating where the word "would be" inserted. It returns -insert-1,
			// where insert is the index of insertion.
			int idx = Arrays.binarySearch(words, word);
			
			if (idx >= 0)
				System.out.println("Yes, that's a valid word.");
			else
				System.out.println("Sorry, that's not a valid word.");
		
			// Get next.
			System.out.println("Do you want to enter another word to search for?");
			response = stdin.next().toLowerCase();
		}
	}
}