larn
larn

Reputation: 398

How to count the occurrence of each letter of the alphabet from a text file in Java?

I'm very new to Java and I'm struggling with my first assignment. The assignment is to scan in a text file (para1.txt) and to read through it and count how many times each letter appears. (So, it should output something like a-57, b-21, c-12, etc.) I feel like I'm very close to the answer, however, I'm having a little trouble actually counting the characters as they appear. Currently, my code prints "17" for all the letters, as there are 17 lines in the para1.txt file. Here is my code so far:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class LetterCounter {
    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("src/para1.txt"));

        int[] count = new int[26];

        while (input.hasNextLine()) {
            String answer = input.nextLine();
            answer = answer.toLowerCase();
            char[] characters = answer.toCharArray();

            for (int i = 0; i < 26; i++) {
                count[i]++;
            }
        }

        for (int i = 0; i < 26; i++) {
            StdOut.print((char) (i + 'a'));
            StdOut.println(": " + count[i]);
        }
    }
}

Upvotes: 0

Views: 4792

Answers (4)

A K
A K

Reputation: 11

Create a hashmap with character as key and count(Integer) as value.Hashmap stores key-value pairs,where key will be unique and put() method is used to insert specific key and value into hashmap.

public class CharCount {
    public static void main(String[] args) {
        File f1 = new File("file-path");
        HashMap<Character, Integer> charMap = new HashMap<Character, Integer>();
        try {
            Scanner in = new Scanner(f1);
            while(in.hasNext()) {
                String inputString = in.nextLine();
                inputString = inputString.replace(" ", "");
                char[] strArray = inputString.toCharArray();
                for (char c : strArray) {
                    if (charMap.containsKey(c)) {
                    // If character is present in charMap, incrementing it's count by 1
                        charMap.put(c, charMap.get(c) + 1);
                    } else {
                        // If char is not present in charMap ,
                        // putting this character to charMap with 1 as it's value
                        charMap.put(c, 1);
                    }
                }
            }
            // Printing the charMap 
            System.out.println(charMap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 1

kai
kai

Reputation: 905

I think you want to take the actual letters and maybe check if you actually have a letter(and not a blank or a number).

public class LetterCounter {
    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("src/para1.txt"));

       int[] count = new int[26];

        while (input.hasNextLine()) {
            String answer = input.nextLine();
            answer = answer.toLowerCase();
            char[] characters = answer.toCharArray();
            /// change here!
            for (int i = 0; i< characters.length ; i++) {
                if((characters[i] >='a') && (characters[i]<='z')) {
                     count[characters[i] -'a' ]++;
                }
            }
            /// change ends.
        }

        for (int i = 0; i < 26; i++) {
            StdOut.print((char) (i + 'a'));
            StdOut.println(": " + count[i]);
        }
    }
}

Upvotes: 2

GBlodgett
GBlodgett

Reputation: 12819

In your loop, you just increment every index of the count Array:

for (int i = 0; i < 26; i++) {
     count[i]++;
}

Instead what you can do is iterate over the characters Array, and increment the index at the char - 'a', to get the correct index:

for(char c : characters) {
   count[c - 'a']++;
}

The only issue with this is that if there are any non alphabetic characters, this will throw an index out of bounds error. You may want to ensure it is in range:

int index = c - 'a';
if(index > 25 || index < 0) {
    System.out.println("Invalid character");
} else {
   //process like normal
}

Upvotes: 1

user10990200
user10990200

Reputation: 33

Maybe you're not supposed to know maps yet but one simple solution would be to use one.

Something like this

HashMap<Character, Integer> chars = new HashMap<>();
for(int i = 0; i < characters.length; i++){
   if(chars.get(characters[i]) == null){
       chars.put(characters[i], 1);
   } else {
      int num = chars.get(characters[i]);
      chars.put(characters[i], num+1); 
}
}

    for(Character c : chars.keyset()){
       print(c + " :" + chars.get(c));
    }

Might be some syntax errors, wrote it here

Upvotes: 0

Related Questions