You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 filename string 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 the while loop. This closes the scanner after the first line is read, causing a crash when the loop tries to check fileScan.hasNext() again.
  • Incorrect counting logic: Your approach to tracking letter counts is flawed—you're overwriting the array with 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?

  1. Proper count tracking: We use an int[] letterCounts array 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.
  2. Processing file content: The inner loop now iterates over each character in the line read from the file, not the filename.
  3. Correct scanner closure: fileScan.close() is moved outside the while loop, so we only close the scanner after reading all lines of the file.
  4. Single output header: The results header and final count printout are done after processing the entire file, so they only appear once.
  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:37:37