0

Im trying to populate the map with the word as the key, and the occurences of that word as the value. The code runs but the results are not accurate. Can anyone see where the code is going wrong here? thanks!

public static void tokenize() {
    

    File file = new File ("textFile.txt");
    
    try {
        FileReader fr = new FileReader(file.getName());
        BufferedReader br = new BufferedReader(fr);
        String line = br.readLine();
        
        while(line!=null) {
            
            String[] array = line.split(" ");
            
            for(String s : array) {
                 
                if(staticHashMap.containsKey(s)) {
                    int value = staticHashMap.get(s);
                    staticHashMap.put(s, value + 1);
                } else {
                    staticHashMap.put(s, 1);
                }
                
            }
            
            line = br.readLine();
            
        }
        
        br.close();
        fr.close();
        
        System.out.println(staticHashMap.get(word));
        
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
            
}
culldog88
  • 83
  • 7
  • `String[] array = line.split(" ");` Are you sure that the words in the file are separated only by one space? What about tabs or punctuation? – chptr-one Mar 21 '21 at 19:30
  • What do you mean by 'results are not accurate'. How do you check that? Do you want to consider upper/lower case? If your text file contains sentences with punctuation that might be one reason (`word` not the same as `word.` or `word,`). – Pascal Mar 21 '21 at 19:32
  • Thats a good point about tabs and punctuations, what is the best approach to storing each word and the number of its occurrences? – culldog88 Mar 21 '21 at 19:36
  • 1
    Does this answer your question? [How to count words in a text file, java 8-style](https://stackoverflow.com/questions/47594679/how-to-count-words-in-a-text-file-java-8-style) Also look at this Q&A: https://stackoverflow.com/questions/29526643/counting-frequency-of-words-from-a-txt-file-in-java/29526969 – Abra Mar 21 '21 at 19:50

0 Answers0