简体   繁体   中英

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

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM