0

In my method, my objective is to store the words in a string into a HashMap. They key will be a word and the result will be the number of times the word occurs.

So far I have attempted the search portion, however, for the part where I increment I left it to just print yes because I have not figured out how to do that either.

So far I am just hoping for the program to print yes for the number of times there is a repeat, however, I am getting an exception for my if statement.

public void countWord(){

    String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");

    for(int i = 0; i < tokens.length; ++i) {
        if(bow.containsKey(tokens[i])) {
            System.out.printf("yes\n");
        }
        else {
            bow.put(tokens[i], 1);
        }
    }
}

I'm assuming bow.containsKey(tokens[i])) is improper syntax and I was wondering how I could replace that.

User9123
  • 675
  • 1
  • 8
  • 20

1 Answers1

1

You need to check the map for a counter for the current token, if it does not exist create one with value 0 and then increment the counter and put it back into the map

public void countWord(){

    String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");

    for(int i = 0; i < tokens.length; ++i) {
        Integer counter = bow.get(tokens[i]);
        if(counter == null) {
            counter = 0;
        }
        bow.put(tokens[i], ++counter);
    }
}

If you want to improve this syntax bow.containsKey(tokens[i])) you can just store the tokens[i] in a variable

public void countWord(){

    String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");

    for(int i = 0; i < tokens.length; ++i) {
        String token = tokens[i];
        Integer counter = bow.get(token);
        if(counter == null) {
            counter = 0;
        }
        bow.put(token, ++counter);
    }
}