import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class CountWords1 { public static ArrayList readWords(String fname) throws FileNotFoundException{ ArrayList list = new ArrayList(); // Open the file File file = new File(fname); Scanner input = new Scanner(file); while(input.hasNext()){ list.add(input.next()); } return list; } public static void checkWord(ArrayList list, String query){ int count = 0; // Number of times that we have seen the // query word //for(String s: list){ for(int i = 0; i < list.size(); ++i){ String s = list.get(i); // Enter once for each String in the list if(s.equalsIgnoreCase(query)) { ++count; } } System.out.println("Found " + query + " " + count + " times"); } /** * @param args */ public static void main(String[] args) throws FileNotFoundException{ // TODO Auto-generated method stub ArrayList list = readWords("/home/fagg/notepad/classes/cs1323/shaks12.txt"); // Show first 20 words for(int i = 0; i < 20; ++i){ System.out.println(list.get(i)); } // Wait for the user to input words & report on the # of times they are in the file Scanner keyboard = new Scanner(System.in); while(keyboard.hasNext()){ checkWord(list, keyboard.next()); } } }