无法找出文件中的句子数
Not able to find out the number of Sentences in a File
我正在编写代码来找出文件中的句子数。
我的代码是:
try{
int count =0;
FileInputStream f1i = new FileInputStream(s);
Scanner sc = new Scanner(f1i);
while(sc.hasNextLine()){
String g = sc.nextLine();
if(g.indexOf(".")!= -1)
count++;
sc.nextLine();
}
System.out.println("The number of sentences are :"+count);
}
catch(Exception e) {
System.out.println(e);
}
我想我的逻辑是正确的,检查周期数。我写了上面的代码,我认为是正确的,但它显示 javautilNoElementfound : No line found
exception 。我尝试了其他一些逻辑,但这个是最容易理解的。但我被困在这里。我在那个异常上使用了 google,它说当我们迭代没有 element.But 我的文件包含数据的东西时抛出它。这个例外有什么办法可以让路吗?还是有其他错误?提示表示赞赏!谢谢
您在 while
循环中调用了 sc.nextLine()
两次,这就是错误发生的原因。
此外,您的逻辑不考虑同一行上有 2 个句子的情况。
你可以尝试这样的事情:
int sentencesPerLine = g.split(".").length;
循环应该是:
while(sc.hasNextLine()){
String g = sc.nextLine();
if(g.indexOf('.')!= -1){//check if the line contains a '.' character
count += g.split("\.").length; // split the line into an array of Strings using '.' as a delimiter
}
}
在 split(...) 方法中,我使用 "\."
而不是 "."
因为 .
是一个正则表达式元素,需要转义。
我正在编写代码来找出文件中的句子数。 我的代码是:
try{
int count =0;
FileInputStream f1i = new FileInputStream(s);
Scanner sc = new Scanner(f1i);
while(sc.hasNextLine()){
String g = sc.nextLine();
if(g.indexOf(".")!= -1)
count++;
sc.nextLine();
}
System.out.println("The number of sentences are :"+count);
}
catch(Exception e) {
System.out.println(e);
}
我想我的逻辑是正确的,检查周期数。我写了上面的代码,我认为是正确的,但它显示 javautilNoElementfound : No line found
exception 。我尝试了其他一些逻辑,但这个是最容易理解的。但我被困在这里。我在那个异常上使用了 google,它说当我们迭代没有 element.But 我的文件包含数据的东西时抛出它。这个例外有什么办法可以让路吗?还是有其他错误?提示表示赞赏!谢谢
您在 while
循环中调用了 sc.nextLine()
两次,这就是错误发生的原因。
此外,您的逻辑不考虑同一行上有 2 个句子的情况。
你可以尝试这样的事情:
int sentencesPerLine = g.split(".").length;
循环应该是:
while(sc.hasNextLine()){
String g = sc.nextLine();
if(g.indexOf('.')!= -1){//check if the line contains a '.' character
count += g.split("\.").length; // split the line into an array of Strings using '.' as a delimiter
}
}
在 split(...) 方法中,我使用 "\."
而不是 "."
因为 .
是一个正则表达式元素,需要转义。