Search code examples
javaif-statementletterfile-iofind-occurrences

Counting letter occurrence


The program needs to count and display the number of times that the specified charector appears in the text file.

Currently turning up zero for the total. I'm not if I should be using a different loop, I've also tried using a 'for' loop.

// Hold user input and sum
String fileName;    // Holds the name of the file
String letter;      // Letter to search for in the file
int total = 0;      // Holds the total number of characters in the file


// Get the name of the file and character from the user
fileName = JOptionPane.showInputDialog("Please enter the name of a file:");
letter = JOptionPane.showInputDialog("Please enter a letter contained in the string");


// Open the file for reading
File file = new File(fileName);         
Scanner inputFile = new Scanner(file);  // Declare new scanner object for file reading


// Set accumulator to zero
int count = 0;

if (inputFile.nextLine().equalsIgnoreCase(letter)) {                                

    count++;          // add letter occurrence

    total += count;   // add the letter occurrence to the total
}

Solution

  •     BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
        int ch;
        char charToSearch='a';
        int counter=0;
        while((ch=reader.read()) != -1) {
            if(charToSearch == (char)ch) {
                counter++;
            }
        };
        reader.close();
    
        System.out.println(counter);
    

    Is this of any help?