【问题标题】:How can I get java to tell me the correct amount of lines and words in a file?如何让 java 告诉我文件中正确的行数和单词数?
【发布时间】:2021-02-13 18:30:14
【问题描述】:

我正在学习如何在课堂上创建一个读取文件的程序。我只能让 java 告诉我文件中正确的字数,而不是正确的行数。如何让 java 告诉我文件中正确的行数和单词数?

公共类阅读器{ public static void main(String args[]) 抛出 IOException {

BufferedReader demo = new BufferedReader(new FileReader("All.txt"));

Scanner file = new Scanner(demo);

int lineCount = 0;
int wordCount = 0;

//单词计数器

while(file.hasNextLine()) {
  String amount = file.nextLine();

  String[] txt = amount.split(" ");
  for(int i = 0; i < txt.length; i++){
    if(txt[i].contains(txt[i]))
    wordCount++;
  }
}
System.out.println("There are  " + wordCount + " words.");

//lineCounter -- 这就是我的问题所在

String line = demo.readLine();
while(line != null){
  lineCount++;
  line = demo.readLine();

}
System.out.println("There are " + lineCount + " lines.");

} }

【问题讨论】:

  • 这里的行是什么意思??一个完整的英文句子??或者当我们遇到退货时?
  • 为什么不一读到行就数行呢?检查if (txt[i].contains(txt[i]))算一个字的目的是什么?
  • @asn21 我的意思是一个完整的句子。
  • 问题在于txt[i].contains(txt[i]) 应该始终为真。字符串总是包含它自己。这种情况应该检测到什么?
  • @Gia,这种情况似乎是真的总是。如果你意思要数句子,那么你应该添加更多逻辑:1)处理句子结尾的不同标点符号:., '?', ! 2 ) 处理案例:一行包含多个句子;一句话跨多行

标签: java file bufferedreader


【解决方案1】:

你可以用这个:

要计算句子,请使用.!? 分割每一行。

计算用空格分割的单词就足够了。

import java.io.*;

public class File {

    public static void main(String[] args) throws IOException {
        
        BufferedReader demo = new BufferedReader(new FileReader("/home/asn/Desktop/All.txt"));
        
        int lineCount = 0;
        int wordCount = 0;
        String line;

        while((line=demo.readLine())!=null)  {
            String[] words = line.split(" ");
            String[] sen = line.split("\\.|\\!|\\?");  // this a a regex expression to split with ., !, and ?

            lineCount += sen.length;
            wordCount += words.length;
          }
          System.out.println("There are  " + wordCount + " words.");
          System.out.println("There are  " + lineCount + " lines.");

          demo.close();
    }
}

【讨论】:

    【解决方案2】:

    你可以在数字的同时数行,如下所示:

    while(file.hasNextLine()) {
      lineCount++;// Add this line
      String amount = file.nextLine();
      String[] txt = amount.split(" ");
      wordCount += txt.length;// Add this line
    }
    System.out.println("There are  " + wordCount + " words.");
    System.out.println("There are  " + lineCount + " lines.");// Add this line
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      相关资源
      最近更新 更多