我在为 Java 类编写程序时遇到问题。作业说明如下:
“文件信件计数器:
编写一个程序,要求用户输入文件名,然后要求用户输入字符。程序应该计算并显示指定字符在文件中出现的次数。使用记事本或其他文本编辑器创建可用于测试程序的示例文件。”
我的教授提供给我们测试这个程序的文本文件有 1307 行随机大小写和放置的字母,这个程序必须经历这些字母,无论出于什么原因,我似乎无法让这个程序正常工作。我尝试过使用迄今为止在课堂和书中学到的知识之外的东西,但我已经迷失了。
输入示例:
f
d
s
h
j
这是我迄今为止的代码(在 NetBeans 23 中编译):
package filelettercounter;
import java.util.Scanner;
import java.io.*;
public class FileLetterCounter {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
do {
int counter = 0;
String line = inputFile.nextLine();
System.out.print("Enter a character: ");
String character = inputFile.nextLine();
if(line.contains(character)) {
counter++;
}
System.out.println("The character " + character + " appears " +
counter + " times in the file.");
}while(inputFile.hasNext());
inputFile.close();
}
}
输出打印了所有 1307 行,显示它们每行出现 0 次...
Enter a character: The character f appears 0 times in the file.
Enter a character: The character d appears 0 times in the file.
Enter a character: The character s appears 0 times in the file.
Enter a character: The character h appears 0 times in the file.
Enter a character: The character j appears 0 times in the file.
...在输出的大部分过程中抛出异常。
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1660)
at filelettercounter.FileLetterCounter.main(FileLetterCounter.java:31)
我需要实现的输出是这样的:
Enter the file name: "filename"
Enter a character: "character"
The character (character) appears (number of times) times in the file.
对于你们中比我经验丰富得多的人的意见,我不应该做任何花哨的事情。作为一个类,我们经历过的最远的事情就是各种循环(for、if/else if/else、do-while、while)、累积变量等。它和基本的获取一样基本。所以,请不要使用列表、数组、分隔符或任何类似的疯狂内容。
您可以解决的三件事:
您的
counter
变量会在每次迭代时重置
每一行中目标字符可以出现多次
只有在迭代完所有行后才应显示输出消息
祝你好运!