no line found exception

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;
        }
    }
}

Answers


while(scanLine.nextLine() != null) {
    String textInput = scanLine.nextLine();
}

I'd say the problem is here:

In your while condition, 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 to scanLine.hasNextLine() or try another approach of reading files.

Another way of reading the txt file can be like this:

BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(new File("text.txt")))));

String line = null;

while ((line = reader.readLine()) != null) {
    // do something with your read line
}
reader.close();

or this:

byte[] bytes = Files.readAllBytes(Paths.get("text.txt"));
String text = new String(bytes, StandardCharsets.UTF_8);

You should use : scanner.hasNextLine() instead of scanner.nextLine() in the while condition

Scanner implements the Iterator interface which works by this pattern:

  • See if there is a next item (hasNext())
  • Retrieve the next item (next())

To count the number of occurrences of "a" or for that matter any string in a string, you can use StringUtils from apache-commons-lang like:

System.out.println(StringUtils.countMatches(textInput,"a"));

I think it will be more efficient than converting the string to character array and then looping over the whole array to find the number of occurrences of "a". Moreover, StringUtils methods are null safe


Need Your Help

Prepopulating form field to meet required condition

javascript jquery html forms

I have a form that in some situations will have a pre populated value. To do this, I am using placeholder. If the placeholder value is not blank, I would like this to meet the required condition. D...

How to delete a character in bash read -d multiline input?

bash readline

I'm writing a bash script that will use readline command to catch user's multiline input (list of packages), but I can't figure out how to delete (backslash) characters while inputing text (let's s...