Untitled
unknown
plain_text
3 years ago
2.5 kB
1
Indexable
Never
import edu.duke.*; import java.util.*; import java.io.*; /** * Write a description of WordsInFiles here. * * @author (your name) * @version (a version number or a date) */ public class WordsInFiles { private HashMap<String, ArrayList<String>> map; public WordsInFiles() { map = new HashMap<String, ArrayList<String>>(); } private void addWordsFromFile(File f) { FileResource fr = new FileResource(f); for (String word: fr.words()) { if (!map.keySet().contains(word)) { ArrayList<String> newArray = new ArrayList<String>(); newArray.add(f.getName()); map.put(word,newArray); } else { if (!map.get(word).contains(f.getName())){ map.get(word).add(f.getName()); } } } } private void buildWordFileMap() { map.clear(); DirectoryResource dr = new DirectoryResource(); for (File f: dr.selectedFiles()) { addWordsFromFile(f); } } private int maxNumber() { int max = 0; for(String word: map.keySet()) { ArrayList<String> array = map.get(word); if(array.size() > max) { max = array.size(); } } return max; } private ArrayList<String> wordsInNumFiles(int number) { ArrayList<String> words = new ArrayList<String>(); for(String word: map.keySet()) { ArrayList<String> files = map.get(word); if (files.size() == number) words.add(word); } return words; } private void printFilesIn(String word) { ArrayList<String> files = map.get(word); for(String file: files) { System.out.println("filename - " + file); } } public void tester() { buildWordFileMap(); int count = 0; int max = maxNumber(); System.out.println("Max is " + max); ArrayList<String> wordsInMax = wordsInNumFiles(4); for (String word: wordsInMax) { System.out.println("For the word " + word); printFilesIn(word); count++; } System.out.println("-----------------"); printFilesIn("tree"); System.out.println("number of words is " + count); } }