您可能在输入时忘记了文件扩展名,但有一种更简单的方法可以做到这一点。您还提到您不知道如何计算字符。你可以试试这样:
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;
import java.util.stream.*;
public class WordCount
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
try {
// Input file
System.out.println("Please enter the name of the file.");
String content = Files.readString(Path.of("C:/Users/garre/OneDrive/Desktop/" + userInput.next()));
System.out.printf("Lines: %d\nWords: %d\nCharacters: %d",content.split("\n").length,Stream.of(content.split("[^A-Za-z]")).filter(x -> !x.isEmpty()).count(),content.length());
}
catch (IOException ex1) {
System.out.println("Error.");
System.exit(0);
}
}
}
浏览代码
import java.util.stream.*;
请注意,我们使用流包,用于在查找单词时过滤掉空字符串。现在让我们向前跳过一点。
String content = Files.readString(Path.of("C:/Users/garre/OneDrive/Desktop/" + userInput.next()));
以上部分获取文件中的所有文本并将其存储为字符串。
System.out.printf("Lines: %d\nWords: %d\nCharacters: %d",content.split("\n").length,Stream.of(content.split("[^A-Za-z]")).filter(x -> !x.isEmpty()).count(),content.length());
好的,这是一条很长的线。让我们分解一下。
"Lines: %d\nWords: %d\nCharacters: %d" 是一个格式字符串,其中每个%d 都替换为printf 函数中的相应参数。第一个%d 将替换为content.split("\n").length,即行数。我们通过拆分字符串得到行数。
第二个%d 被Stream.of(content.split("[^A-Za-z]")).filter(x -> !x.isEmpty()).count() 替换。 Stream.of 从一个数组创建一个流,并且该数组是一个字符串数组,在您拆分任何非字母(您说单词是任何非字母)之后。接下来,我们过滤掉所有的空值,因为String.split 保留了空值。 .count() 是不言自明的,它采用过滤后剩余的字数。
第三个也是最后一个%d 是最简单的。它被字符串的长度替换。 content.length() 应该是不言自明的。
我保留了您的catch 块完好无损,但我觉得System.exit(0) 有点多余。