Java 计算单词和字符

标签 java string text-files

我应该创建一个程序来计算文本文件中的单词数和平均字符数(不含空格)。我已经创建了该程序,我只是遇到一个问题。我的字符总数计数器计算字符“-”和“.”。在计算字数时,我不希望这种情况发生。目前我正在统计 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/

相关文章:

c - 如何在 C 中对 .txt 文件内的数据进行排序

python - 如何在 python 中打开一个文本文件并只将第一个可见部分写入屏幕?

php - 更改 PHP 以从 mysql 数据库而不是 .txt 文件获取图像 url

string - 哪一个是将 String 转换为 ByteString 的正确方法?

java - java中的十六进制到int数字格式异常

java - 导入新 Gradle 项目失败 : failed to find Build Tools revision *. 0.0

java - Hibernate 查询返回错误的日期

javascript - D3.js - 在图表中添加和自定义文本

c++ - 需要有关从字符串中获取字符的帮助吗?

java - play framework 2.0 中的 Cron Job