1

So my task was to create a program that takes a file as input and counts the occurrences of each alphabetic character in it. Then I shall print the letter, the amount of times it occurs and the frequency of it. And I get it to work almost as planned. The only problem I have is that when I print, it also prints the number of dots(.) in the file. And I can't stop it from doing that. Help please..

public class CountOccurences {
private static Scanner input;

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

    DecimalFormat dec = new DecimalFormat("#.000");
    input = new Scanner(new File("story.txt"));

    int[] ltrCtr = new int[127]; // This array counts the number of occurences for every letter / symbol on the ascii table. 

    String str = "";
    // Puts the textfile as a String
    while(input.hasNext()) {
        str += input.next();
    }

    char[] text = str.toCharArray();

    char temp; int tempInt;
    int ctr = 0;

    for(int i = 0; i < text.length; i++) { // Loops through the text 

        temp = text[i]; // Gets the char at i
        tempInt = (int)temp; // Get the ascii value of the char at i  

        ltrCtr[tempInt]++;  

        if(Character.isAlphabetic(text[i])) {
            ctr++;
        }
    }
    System.out.println("Letter" + "     Amount" + "     Freq");
    for(int i = 0; i < ltrCtr.length; i++) {
        if(ltrCtr[i] >= 1 && (int)ltrCtr[i] != 46) {
            System.out.println("   " + (char)i  + "          " +  
                    ltrCtr[i] + "        " + 
                    dec.format((double)ltrCtr[i]/ctr) + "%");

        }
    }

    input.close();

}

}

Nudd3
  • 29
  • 4
  • 1
    Note that your code will crash (IndexOutOfBoundsException) if you have anything other than basic ASCII text (for example, accented characters or Unicode) because a `char` is [16 bits](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html). So you should only increment `ltrCtr` inside the `Character.isLetter()` test. Also, for some reason you appear to be ignoring any character that appears precisely 46 times, and you need to multiply by 100.0 to get a percentage. – DavidW May 29 '18 at 17:47
  • You're right. Hadn't made enough tests. Thanks you! – Nudd3 May 30 '18 at 00:34

2 Answers2

0

I believe you meant to use isLetter, not isAlphabetic.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Mureinik is right, isLetter solves your problem. Here's a post explaining the differences between isLetter and isAlphabetic to make it clearer: What is the difference between Character.isAlphabetic and Character.isLetter in Java?