Search code examples
javabluej

Counting the amount of times each letter shows in a file


Essentially, this code takes a file (which is a few paragraphs of text) and counts the amount of times each letter appears and prints it onto the console. While I've finished all the code in terms of calculation, I'm running into an exception. When I run this, it shows:

java.util.NoSuchElementException

at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at LetterCount.countOccurrences(LetterCount.java:29)
at LetterCount.main(LetterCount.java:20)

Here is my code:

// Document your class here

import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
public class LetterCount {

public final static String FILENAME = "testFile.txt";

// Driver to test LetterInventory class
public static void main(String[] args) {
    Scanner inputFile = null;
    try {
        inputFile = new Scanner(new File(FILENAME));
    } catch (Exception e) { 
        System.out.println("File could not be opened: " + FILENAME);
        System.exit(0);
    }

    int[] counts = countOccurrences(inputFile);
    displayTable(counts);
    resetTable(counts);  
}

public static int[] countOccurrences (Scanner inputFile) {
    int[]counts = new int[26];
    char[] characters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    while (inputFile.hasNextLine()) {
        String theWord = inputFile.next();
        theWord = theWord.toLowerCase();

        for (int j = 0; j < theWord.length(); j++) {
            for (int counter = 0; counter < 26; counter++) {
                if (theWord.charAt(j) == characters[counter]) {
                    counts[counter] += 1;
                }

            }
        }
    }
    return counts;
}

public static void displayTable (int[] counts) {
    for (int index = 0; index < 26; index++) {
        System.out.println((char)('a' + index) + ":\t" + counts[index]);
    }
}

public static void resetTable (int[] counts) {
    System.out.println();
    for (int index = 0; index < 26; index++) {
        System.out.println((char)('a' + index) + ":\t0");
    }
}
}  

When I clicked on the highlighted parts of NoSuchElementException, I saw that it was referring to the String I created. What am I doing wrong, and what can I do to fix it?


Solution

  • The method you use to read the data should be of the same type as the one you use to check if there is more data.

    In your while statement, you use inputFile.hasNextLine(), so on the line after it, you should use inputFile.nextLine() (rather than inputFile.next() as you do now).

    Alternatively, you can change the while statement to use inputFile.hasNext().