如何解决如何使java告诉我文件中正确的行数和单词数?
我正在学习如何创建一个在课堂上读取文件的程序。我只能让java告诉我文件中单词的正确数量,而不是行数。如何让Java告诉我文件中正确的行数和单词数?
公共类读者{ 公共静态void main(String args [])引发IOException {
BufferedReader demo = new BufferedReader(new FileReader("All.txt"));
Scanner file = new Scanner(demo);
int lineCount = 0;
int wordCount = 0;
// wordCounter
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
,
您可以使用此:
要计算句子数,请用.
,!
,?
分隔每一行。
计算空格分隔的单词就足够了。
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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。