4
\$\begingroup\$

This program prompts the user to enter a file name and displays the occurrences of each letter in the file. Is there a simpler and more efficient way to do this? Please, help me figure this out. Thanks!

import java.io.*;
import java.util.Scanner;
public class OccurenceOfEachLetter {
    public static void main(String[] args) {
        //declares variables
        String[] sentence = new String [23];
        int countA = 0;
        int countB = 0;
        int countC = 0;
        int countD = 0;
        int countE = 0;
        int countF = 0;
        int countG = 0;
        int countH = 0;
        int countI = 0;
        int countJ = 0;
        int countK = 0;
        int countL = 0;
        int countM = 0;
        int countN = 0;
        int countO = 0;
        int countP = 0;
        int countQ = 0;
        int countR = 0;
        int countS = 0;
        int countT = 0;
        int countU = 0;
        int countV = 0;
        int countW = 0;
        int countX = 0;
        int countY = 0;
        int countZ = 0;
        char words;
        //Get user input 
        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter a Filename: ");
        String filename = keyboard.nextLine();

        //Open file for reading
        Scanner inputStream = null;

        //catch exception
        try 
        {
            inputStream = new Scanner(new File(filename)); 
        }
        catch(FileNotFoundException e)
        {
            System.out.print("Error opening the " + filename);
            System.exit(0);
        }

        //read form file and store in an array
        while(inputStream.hasNextLine()) 
        {
            for (int i = 0; i < sentence.length; i++) 
            {
                sentence[i] = inputStream.nextLine();
                //counts the occurrence of each letter in each line of gettysburg.txt
                for(int j = 0; j < sentence[i].length() ;j++) 
                { 
                    words = sentence[i].charAt(j);
                    if(words == 'A' || words == 'a') 
                    {
                        countA++;

                    }
                    if(words == 'B' || words == 'b') 
                    {
                        countB++;

                    }
                    if(words == 'C' || words == 'c') 
                    {
                        countC++;

                    }
                    if(words == 'D' || words == 'd') 
                    {
                        countD++;

                    }
                    if(words == 'E' || words == 'e') 
                    {
                        countE++;

                    }
                    if(words == 'F' || words == 'f') 
                    {
                        countF++;

                    }
                    if(words == 'G' || words == 'g') 
                    {
                        countG++;

                    }
                    if(words == 'H' || words == 'h') 
                    {
                        countH++;

                    }
                    if(words == 'I' || words == 'i') 
                    {
                        countI++;

                    }
                    if(words == 'J' || words == 'j') 
                    {
                        countJ++;

                    }
                    if(words == 'K' || words == 'k') 
                    {
                        countK++;

                    }
                    if(words == 'L' || words == 'l') 
                    {
                        countL++;

                    }
                    if(words == 'M' || words == 'm') 
                    {
                        countM++;

                    }
                    if(words == 'N' || words == 'n') 
                    {
                        countN++;

                    }
                    if(words == 'O' || words == 'o') 
                    {
                        countO++;

                    }
                    if(words == 'P' || words == 'p') 
                    {
                        countP++;

                    }
                    if(words == 'Q' || words == 'q') 
                    {
                        countQ++;

                    }
                    if(words == 'R' || words == 'r') 
                    {
                        countR++;

                    }
                    if(words == 'S' || words == 's') 
                    {
                        countS++;

                    }
                    if(words == 'T' || words == 't') 
                    {
                        countT++;

                    }
                    if(words == 'U' || words == 'u') 
                    {
                        countU++;

                    }
                    if(words == 'V' || words == 'v') 
                    {
                        countV++;

                    }
                    if(words == 'W' || words == 'w') 
                    {
                        countW++;

                    }
                    if(words == 'X' || words == 'x') 
                    {
                        countX++;

                    }
                    if(words == 'Y' || words == 'y') 
                    {
                        countY++;

                    }
                    if(words == 'Z' || words == 'z') 
                    {
                        countZ++;

                    }
                }
            }
        }//end while

        //close file
        inputStream.close();

        //Displays results
        System.out.println("The file gettysburg.txt contains the following: ");
        for(char i = 65 ; i <= 90;) 
        {
            int[] count = {countA, countB, countC, countD, countE, countF, countG, countH, countI, countJ, countK, countL, countM, countN, countO, countP, countQ, countR, countS, countT, countU, countV, countW, countX, countY, countZ};
            for(int j = 0; j< count.length;) 
            {
                System.out.println("Number of " + i +"'s: " + count[j]);
                j++;
                i++;
            }
        }
    }//ends main
}//ends class
\$\endgroup\$
4
\$\begingroup\$

Welcome to CodeReview! Especially as a beginner programmer, it takes bravery to show your code to the internet, but you've taken the first step.

This code has a long way to go, but I think it'll be a good learning experience for you.

//declares variables

Keep in mind that this isn't 1989-era C, so you don't need to predeclare all of your variables at the top of methods. Declare them where they're actually used.

String[] sentence = new String [23];

What is the number 23? This is a so-called magic number. If it really needs to be in the program, it should be put in its own named constant. However, I suspect that this is the number of lines of input. First: you already have logic to quit once you find the end of the file. Also: why store every line? You only need to store the results of letter summation, not the raw input. So this array is not necessary.

inputStream = new Scanner(new File(filename)); 

Google "try-with-resources". This will make it so that your program will close the file even if something goes wrong in the middle.

for (int i = 0; i < sentence.length; i++) 

This loop can go away entirely. The while above it already iterates through the lines of the file.

int countA = 0;

You should not have each of these as individual values. You arrived at the right idea later on with the count array. All of those individual letter count variables should go away and you should operate on the array directly.

\$\endgroup\$
2
\$\begingroup\$

I focus on the operation of storing occurrences of single letters of a sentence in an array of ints and after print the number of occurrences for every single letter, I'm assuming that we are using the english alphabet:

int[] occurrences = new int[26];

Now start to examine a sentence and convert it to a char array:

String sentence = "Gettysburg, PA";
char[] arr = sentence.toCharArray();
final char initial = 'a';

You want to store only letters as case insensitive so for example occurrences of chars A and a will be stored in the same position of the occurrences array, you can do in this way:

for (char ch : arr) {
    if (Character.isLetter(ch)) {
        char ch_lower = Character.toLowerCase(ch);
            ++occurrences[ch_lower - initial];
    }
}

You can refer to Character documentation for further details about methods I used in the loop. Now you can print all the occurrences in the array:

String format = "Number of %c: %d";
for(int i = 0; i < 26; ++i) {
    System.out.println(String.format(format, initial + i, occurrences[i]));
}

I used the method String.format for improve readibility of print code. Below the code you can test:

public static void main(String[] args) {

    int[] occurrences = new int[26];


    final char initial = 'a';   
    String sentence = "Gettysburg, PA";
    char[] arr = sentence.toCharArray();
    for (char ch : arr) {
        if (Character.isLetter(ch)) {
            char ch_lower = Character.toLowerCase(ch);
            ++occurrences[ch_lower - initial];
        }
    }
    String format = "Number of %c: %d";
    for(int i = 0; i < 26; ++i) {
        System.out.println(String.format(format, initial + i, occurrences[i]));
    }

}
\$\endgroup\$
  • \$\begingroup\$ This is not equivalent. You need to open a file. \$\endgroup\$ – Reinderien Sep 1 at 12:07
  • \$\begingroup\$ @Reinderien Hello, I wrote at the start of my answer that my focus is about storing occurrences of single letters of a sentence in an array of ints and after print them. \$\endgroup\$ – dariosicily Sep 1 at 14:04
2
\$\begingroup\$

Perhaps the next piece of code may be overwhelming for a Java beginner, due to the fact that it uses advanced features of the language such as streams, lambdas, and try-with-resource clauses. However, just for showing a different approach using functional programming, your program could be rewritten as follows:

   public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter a Filename: ");
            Path file = Paths.get(scanner.next());
            try (Stream<String> lines = Files.lines(file)) {
                System.out.println("The file "+file+" contains the following: ");
                lines
                    .flatMapToInt(String::chars)
                    .filter(Character::isAlphabetic)
                    .map(Character::toLowerCase)
                    .mapToObj(c->(char)c)
                    .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
                    .forEach((letter,count)->System.out.println("Number of "+letter+"'s: "+count));
            } catch (IOException e) {
                System.out.println("Error opening the file "+file);
                System.exit(0);
            }
        }
   }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.