Reputation: 147
I am writing a code to find out the number of sentences in a file. My code is as :
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);
}
I guess my logic is right to check for the number of periods. I wrote the above code which i think is right but it displays a javautilNoElementfound : No line found
exception . I tried some other logics but this one was the best understandable. But i am stuck here. I used google on that exception and it says that it is thrown when we iterate over something that has no element.But my file contains data. Is there some way this exception could have made way?? Or is there some other error? Hints are appreciated ! Thanks
Upvotes: 0
Views: 38
Reputation: 22474
You are calling sc.nextLine()
two times inside the while
loop that is why the error occurs.
Also your logic doesn't account for cases when there are 2 sentences on the same line.
You can try something like this:
int sentencesPerLine = g.split(".").length;
The loop should be:
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
}
}
In the split(...) method I'm using "\\."
instead of "."
because .
is a regex element and needs to be escaped.
Upvotes: 2