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

Java文件字符统计代码输出不符,请求排查错误

代码输出不符合预期的排查分析

评分器十分严苛,我花了30分钟排查代码错误却毫无头绪。

我的代码

import java.util.Scanner;
import java.io.*;
public class FileLetterCounter
{
    public static void main(String[] args) throws IOException
    {
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter file name: ");
        String filename = scan.nextLine();
        File afile = new File(filename);
        Scanner input = new Scanner(afile);
    
        System.out.print("Enter character to count: ");
        char character = input.next().charAt(0);
    
       String line;
       int count = 0;
    
       while (input.hasNext())
        {
            line = input.nextLine();
            for (int a=0;a<line.length();a++)
            {
               if (line.charAt(a)==character) 
               {
                   count++;
               }
            }
        }
         input.close();
         System.out.printf("The character '%c' appears in the file %s %d times.", character, filename, count);
     }

 }

预期输出

Enter file name: mydata.txt
Enter character to count: a
The character 'a' appears in the file mydata.txt 17 times.

错误提示

Checking output
Your standard output is not what was expected.

问题排查与修复

核心错误点

  • 字符读取源逻辑错误:你用读取文件的input Scanner获取要统计的字符,这会直接从文件开头读取第一个字符,而非读取用户在控制台输入的字符,完全偏离需求逻辑。
  • 换行符遗留导致统计遗漏:即便读取逻辑正确,input.next()执行后会遗留换行符,后续input.nextLine()会先读取这个空行,导致文件第一行被跳过,统计结果少了第一行的字符数量。

修正后的代码

import java.util.Scanner;
import java.io.*;
public class FileLetterCounter
{
    public static void main(String[] args) throws IOException
    {
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter file name: ");
        String filename = scan.nextLine();
        File afile = new File(filename);
        Scanner input = new Scanner(afile);
    
        System.out.print("Enter character to count: ");
        // 改用读取控制台的scan获取目标字符
        char character = scan.next().charAt(0);
    
        String line;
        int count = 0;
    
        // 用hasNextLine更贴合按行读取的逻辑
        while (input.hasNextLine())
        {
            line = input.nextLine();
            for (int a=0;a<line.length();a++)
            {
               if (line.charAt(a)==character) 
               {
                   count++;
               }
            }
        }
        input.close();
        scan.close();
        System.out.printf("The character '%c' appears in the file %s %d times.", character, filename, count);
    }
}

修正说明

  1. 修正字符读取来源:用scan.next().charAt(0)从控制台获取用户输入的目标字符,确保逻辑符合需求。
  2. 优化文件读取判断:用input.hasNextLine()替代input.hasNext(),更适配按行读取文件的场景。
  3. 补充资源关闭:添加scan.close()关闭控制台输入的Scanner,避免资源泄漏。

内容的提问来源于stack exchange,提问作者Mot J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:52:48