Question

I am trying to add two lines from tableLineScanner, which get's it's lines from a Scanner called tableScanner.

Anyhow, I get these errors

    at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Database.main(Database.java:77)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

But as in the code bellow, I can't understand why I get this error. Since I check if their is two lines available and there by not engage.

if((tableLineScanner.hasNextLine()&&(tableLineScanner.hasNextLine()))){  //Checks if it exists two available lines.
  fieldInput = (tableLineScanner.next() + " " + (tableLineScanner.next().replaceAll("[()]", ""))+",");
  tableFields.add(fieldInput);
  System.out.println("ADDING: " + fieldInput + " to tableField array list");
}

Please help :(

Was it helpful?

Solution

The method Scanner#hasNextLine() just tells you if there is one more line available. If you call it twice, it will still just tell you, if there is ONE more line available. You can call it n times, but it will just tell you about the next line.

Call Scanner#nextLine() and then you can test again if there is another line available.

Always do it that way:

  1. Test if more data is available
  2. Read data
  3. Test if more data is available
  4. ...

if (tableLineScanner.hasNextLine()) {
    String firstLine = tableLineScanner.nextLine();

    if (tableLineScanner.hasNextLine()) {
        String secondLine = tableLineScanner.nextLine().replaceAll(...);

        tableFields.add(firstLine + secondLine);
    } else {
        // No-second-line error handling goes here
    }
} else {
    // No-first-line error handling goes here (if any)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top