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.
问题排查与修复
核心错误点
- 字符读取源逻辑错误:你用读取文件的
inputScanner获取要统计的字符,这会直接从文件开头读取第一个字符,而非读取用户在控制台输入的字符,完全偏离需求逻辑。 - 换行符遗留导致统计遗漏:即便读取逻辑正确,
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); } }
修正说明
- 修正字符读取来源:用
scan.next().charAt(0)从控制台获取用户输入的目标字符,确保逻辑符合需求。 - 优化文件读取判断:用
input.hasNextLine()替代input.hasNext(),更适配按行读取文件的场景。 - 补充资源关闭:添加
scan.close()关闭控制台输入的Scanner,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Mot J
相关产品推荐
相关产品推荐

