Help again guys, why do I always get this kind of error when using scanner, even though I’m sure that the file exists.
java.util.NoSuchElementException: No line found
I am trying to count the number of occurences of a by using for loop. the text file contain lines of sentence. At the same time, I want to print the exact format of sentences.
Scanner scanLine = new Scanner(new FileReader("C:/input.txt"));
while (scanLine.nextLine() != null) {
String textInput = scanLine.nextLine();
char[] stringArray = textInput.toCharArray();
for (char c : stringArray) {
switch (c) {
case 'a':
default:
break;
}
}
}
I’d say the problem is here:
In your
whilecondition, you scan the last line and come to EOF. After that, you enter loop body and try to get next line, but you’ve already read the file to its end. Either change the loop condition toscanLine.hasNextLine()or try another approach of reading files.Another way of reading the txt file can be like this:
or this: