Java文本文件字母统计程序异常:读取文件名而非内容后崩溃
Fixing Letter Frequency Counter Program Issues
Let's break down what's going wrong with your code and fix it step by step:
Key Problems in Your Current Code
- Processing the filename instead of file content: Your inner loop iterates over the
filenamestring instead of the actual text lines you read from the file. That's why you're seeing characters from the filename in your output. - Closing the file scanner too early: You call
fileScan.close()inside thewhileloop. This closes the scanner after the first line is read, causing a crash when the loop tries to checkfileScan.hasNext()again. - Incorrect counting logic: Your approach to tracking letter counts is flawed—you're overwriting the
arraywith filename characters and using the character itself as the count value, which makes no sense. - Misplaced output: The header "Letters - Frequencies in file:" is printed inside the loop, so it will repeat for every line in the file instead of appearing once at the start.
Corrected Code
Here's the fixed version that properly counts letter frequencies from the file content:
/* * Program that reads in a text file and counts the frequency of each letter * Displays the frequencies in descending order */ import java.util.*; // Needed for Scanner import java.io.*; // Needed for File related classes public class LetterCounter { public static void main(String args[]) throws IOException{ Scanner keyboard = new Scanner(System.in); System.out.println("Enter the name of the text file to read:"); String filename = keyboard.next(); keyboard.close(); // Close the input scanner after getting the filename String alphabet = "abcdefghijklmnopqrstuvwxyz"; // Initialize an array to track counts: index 0 = 'a', 1 = 'b', ..., 25 = 'z' int[] letterCounts = new int[26]; Scanner fileScan = new Scanner(new File(filename)); // Loop through each line in the file while (fileScan.hasNextLine()) { String line = fileScan.nextLine().toLowerCase(); // Convert line to lowercase // Iterate over each character in the current line for (char c : line.toCharArray()) { int index = alphabet.indexOf(c); // Only count if the character is a letter (index != -1) if (index != -1) { letterCounts[index]++; } } } fileScan.close(); // Close the file scanner after processing all lines // Print the final results System.out.println("Letters - Frequencies in file:"); for (int i = 0; i < letterCounts.length; i++) { char letter = alphabet.charAt(i); System.out.printf("Number of Occurrence of %c is: %d%n", letter, letterCounts[i]); } } }
What Changed?
- Proper count tracking: We use an
int[] letterCountsarray where each index corresponds to a letter (0 for 'a', 1 for 'b', etc.). Every time we find a letter in the file, we increment the corresponding array position. - Processing file content: The inner loop now iterates over each character in the line read from the file, not the filename.
- Correct scanner closure:
fileScan.close()is moved outside thewhileloop, so we only close the scanner after reading all lines of the file. - Single output header: The results header and final count printout are done after processing the entire file, so they only appear once.
- Letter validation: We check if
alphabet.indexOf(c)returns a valid index (not -1) to ensure we only count actual letters, ignoring punctuation, spaces, etc.
Testing this with your sample input Hi, I like to play sports. will give you the expected output, showing counts like i: 3, h:1, a:1, etc.
内容的提问来源于stack exchange,提问作者ThatBoy123
相关产品推荐
相关产品推荐

