HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Counting five specific words in a file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filecountingfivewordsspecific

Problem

I'm trying to improve my code and i want to know if this is the best way to write this Switch or if there are other methods.

for(String word : words) {
        switch(word.toLowerCase()) {
        case "a":
            a++;
            break;
        case "the":
            the++;
            break;
        case "bird":
            bird++;
            break;
        case "animal":
            animal++;
            break;
        case "is":
            is++;
            break;
        }
    }


Here is the complete code if you need it.

public static void main(String[] args) throws IOException {
ArrayList words = new ArrayList<>();
int a = 0, the = 0, bird = 0, animal = 0, is = 0;

    for(String line : Files.readAllLines(Paths.get("C:\\Users\\n\\Desktop\\Text.txt"))) {
        line.split("\\s+");
        line.replaceAll("[!?.,]", "");
        for(String word : line.split("\\s+")) {
            words.add(word);
        }
    }

    for(String word : words) {
        switch(word.toLowerCase()) {
        case "a":
            a++;
            break;
        case "the":
            the++;
            break;
        case "bird":
            bird++;
            break;
        case "animal":
            animal++;
            break;
        case "is":
            is++;
            break;
        }
    }
System.out.println(a + " " + the + " " + bird + " " + animal + " " + is);
}

Solution

You can use a Map :

Map freq = new HashMap();
for(String word : words) {
    String w = word.toLowerCase();
    if (freq.containsKey(w)) {
        freq.put(w,freq.get(w)+1);
    } else {
        freq.put(w,1);
    }
}

Code Snippets

Map<String,Integer> freq = new HashMap<String,Integer>();
for(String word : words) {
    String w = word.toLowerCase();
    if (freq.containsKey(w)) {
        freq.put(w,freq.get(w)+1);
    } else {
        freq.put(w,1);
    }
}

Context

StackExchange Code Review Q#73486, answer score: 10

Revisions (0)

No revisions yet.