user2140783
user2140783

Reputation: 39

Finding duplicates in an array and adding it to the count

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];

}

Upvotes: 0

Views: 338

Answers (1)

Fabien
Fabien

Reputation: 13406

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.

Upvotes: 4

Related Questions