0

I've got an issue with some current code. I finished the first half, but now I'm using a hashMap to search this imported text document and find the most used word and the number of times it appears. I had a lot of syntax written and my professor said it was a little extraneous so I whittled it down some. The problem I'm having is with entrySet, which we have to use. I've gotten it to this point, but I'm having an issue implementing it. Any help would be great, I'm just unfamiliar with the entrySet concept but I've read through the documentation.

Thanks, here's the code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class HashMapPractice {

public static void main(String[] args) throws FileNotFoundException{

    Scanner file = new Scanner(new File("crime_and_punishment.txt"));

    Map<String, Integer> crimeMap= new HashMap<String, Integer>();

    while (file.hasNext()){
        String word = file.next();
        if(crimeMap.containsKey(word)){
            int placeholder = crimeMap.get(word) + 1;
            crimeMap.put(word, placeholder);
        }else{
            crimeMap.put(word, 1);
        }   
    }//ends while loop

    Set<Map.Entry<String,Integer>> entrySet = crimeMap.entrySet();


    for(Map.Entry<String, Integer> ent : entrySet){
        String key = ent.getKey();
        Integer value = ent.getValue();

        System.out.printf("Word: [" + ent.getKey()+"], Times: ["  +   

         ent.getValue()+"]");
    }
}//ends main
}//ends class
guitar138
  • 33
  • 1
  • 1
  • 7
  • Sorry everyone, I forgot to include the last part so I just edited it. I have every word of the text file printing out with the number of times it's in the file, but i need it to only print the one with the most occurences. – guitar138 Mar 30 '15 at 19:59
  • well, if you only need to print the one with most occurrences then, you could create a temp variable which store the most occurrence and then print it out after you check the entrySet variable. – kucing_terbang Mar 31 '15 at 04:03
  • Awesome, that makes perfect sense. Thank you! Finally got that working after messing with it for a bit – guitar138 Apr 01 '15 at 02:09

0 Answers0