while (myFile.hasNextLine()) {
if(myFile.next().equals("Oval")) {
System.out.println("this is an Oval");
}
else if(myFile.next().equals("Rectangle")) {
System.out.println("this is an Rectangle");
}
the file contains the following
Oval 10 10 80 90 Red
Oval 20 20 50 60 Blue
Rectangle 10 10 100 100 Green
I want to extract the data and pass them to a specific constructor according to the type indicated at the beginning of the line.
but I am getting this weird output
this is an Oval Exception in thread "main" java.util.NoSuchElementException this is an Rectangle at java.util.Scanner.throwFor(Scanner.java:907) this is an Rectangle at java.util.Scanner.next(Scanner.java:1416) at TestMain.main(TestMain.java:33) 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:601) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code 1
Understand that when you call
next()
on a Scanner object, it eats the next token, and then returns it to you. If you don't assign the String returned to a variable, it's lost forever, and the next time you callnext()
you get a new token. Much better to get the token, assign it to a String variable and then do your if tests. Don't callnext()
in the if boolean test block.i.e., something like:
Also, if you test for
hasNextLine()
then you should callnextLine()
, notnext()
, and you should call it only once for each hasNextLine.When extracting lines of data from a text file, I sometimes use more than one Scanner. For instance:
You need to match your
next()
with ahasNext()
method call to match an individual String token