首页 > 解决方案 > 如何让 java 告诉我文件中正确的行数和单词数?

问题描述

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

公共类阅读器{公共静态无效主(字符串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.");

} }

标签: javafilebufferedreader

解决方案


您可以在计算单词的同时计算行数,如下所示:

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

推荐阅读