java - 如何让 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.");
} }
解决方案
您可以在计算单词的同时计算行数,如下所示:
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
推荐阅读
- javascript - 序列化后如何使用 getter 恢复 TypeScript 私有属性?
- java - 如何从列表中删除重复项?
- php - 如何提高 PHP curl 的性能
- javascript - 来自 php 的 echo char(128) 及更高版本不起作用
- c# - 如何使用 C#.NET 类/DLL 创建 C++ DLL
- java - 在每个间隔后更改帧的显示,就像动画一样
- android - Handler() 已弃用
- docker - docker sed arg 变量没有被使用
- reactjs - 出现错误:找到以下环境的绑定:-在我的 ubuntu 系统中使用 Node.js 9.x 的 Linux 64 位
- mysql - 在用户输入之前匹配特定字符串