gpt4 book ai didi

Java 计算单词和字符

转载 作者:行者123 更新时间:2023-12-02 11:36:08 26 4
gpt4 key购买 nike

我应该创建一个程序来计算文本文件中的单词数和平均字符数(不含空格)。我已经创建了该程序,我只是遇到一个问题。我的字符总数计数器计算字符“-”和“.”。在计算字数时,我不希望这种情况发生。目前我正在统计 300 个字符。有四个 ”。”应该从计数器中删除一个“-”,这样我就可以获得 295 的总值。我尝试使用 char,但遇到错误,不允许我将字符串与 char 进行比较。我的 friend 建议我应该尝试采用一种方法来比较 char 和 Unicode,但我不知道如何开始编写代码。

public class Count {

public static void main(String[] args) {

File sFile = new File("s.txt");
FileReader in;
BufferedReader readFile;
String sourceCode;
int amountOfWords = 0;
int amountOfChars = 0;

try {
in = new FileReader(sFile);
readFile = new BufferedReader(in);
while ((sourceCode = readFile.readLine()) != null) {
String[] words = sourceCode.split(" ");
amountOfWords = amountOfWords + words.length;
for (String word : words) {
amountOfChars = amountOfChars + word.length();
}
}
System.out.println("Amount of Chars is " + amountOfChars);
System.out.println("Amount of Words is " + (amountOfWords + 1));
System.out.println("Average Word Length is "+ (amountOfChars/amountOfWords));
readFile.close();
in.close();
} catch (FileNotFoundException e) {
System.out.println("File does not exist or could not be found.");
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}

最佳答案

做之前

String[] words = sourceCode.split(" ");

使用replace删除所有不需要的字符

例如

sourceCode = sourceCode.replace ("-", "").replace (".", "");
String[] words = sourceCode.split(" ");

关于Java 计算单词和字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48917826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com