简体   繁体   中英

how to extract data from text file in Java

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 call next() 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 call next() in the if boolean test block.

ie, something like:

while (myFile.hasNextLine()) {

    // get the token **once** and assign it to a local variable
    String text = myFile.nextLine();

    // now use the local variable to your heart's content    
    if(text.equals("Oval")) {
        System.out.println("this is an Oval");

    }

    else if(text.equals("Rectangle")) {
        System.out.println("this is an Rectangle");

    } 

Also, if you test for hasNextLine() then you should call nextLine() , not next() , 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:

Scanner fileScanner = new Scanner(myFile);
while (fileScanner.hasNextLine()) {
  Scanner lineScanner = new Scanner(fileScanner.nextLine());

  // use the lineScanner to extract tokens from the line

  lineScanner.close();
}
fileScanner.close(); // likely done in a finally block after null check

You need to match your next() with a hasNext() method call to match an individual String token

while (myFile.hasNext()) {
   String token = myFile.next();

    if (token.equals("Oval")) {
       System.out.println("this is an Oval");
    }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM