0

My code below takes in all the words from a txt file and beside it prints out the number 1(count). The aim of my program is to take in all the words like its doing but if it is a duplicate i don't want it to print the word I want it to find its match and add one to its count.

Scanner in = new Scanner(new File(filename));
int i = 0;
int n = 1;
String w = "";
String txt = "";

while ((in.hasNext())) {
    w = in.next() ;
    wrd[i] = w;
    num[i] = n;
    i++;
    txt = wrd[i];

}
1
  • A suggestion - AVOID using Scanner for reading from a File. What wrong has FileReader done to you? Commented Mar 7, 2013 at 16:09

1 Answer 1

4

You want to use a Map :

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

while (in.hasNext()) {
    String w = in.next();

    if (map.containsKey(w)) {  // Already in the map
        map.put(w, map.get(w) + 1);  // Increment the counter
    } else {  // First time w is found, initialize the counter to 1
        map.put(w, 1);
    }
}

Basically, the map is associating a key (here, the words you want to count) to a value (the # of occurrences of the current word). containsKey checks whether some value was associated with the given key yet, get retrieves that value (if any) and put sets a new value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.