简体   繁体   中英

Java - Scanner won't recognize double value from file

I am trying to save values from a tab-separated file into a class. My problem is that my scanner will not recognize the last token as a double.

My file:

    Saint Lucia 179667  0.46
    Bosnia & Herzegovina    3503554 -0.10
    Tajikistan  9107211 2.08

The code that throws the error:

    while (fiSc.hasNextLine()) {
        temp.add(new Country(fiSc));
    }

Constructor for Country class:

    public Country(Scanner fiSc) {
        name = fiSc.next();
        pop = fiSc.nextInt();
        rate = fiSc.nextDouble();
    }

Temp is a LinkedList of the type Country where I am storing the file information. Country holds the name (String), population (int), and growth rate (double). I have tried constructing the Country class by first creating the object and adding the object after, however, I was able to pinpoint the problem to the last token.

When I try this code:

        while (fiSc.hasNextLine()) {
            System.out.println(fiSc.next());
            System.out.println(fiSc.nextInt());
            System.out.println(fiSc.nextDouble());
        } 

I get:

    Saint Lucia
    179667
    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextDouble(Unknown Source)
    at MyMain.fillList(MyMain.java:61)
    at MyMain.main(MyMain.java:11)

I think the problem is not in your code but in your input file.
Your input file looks like that every new line begins with a tab character and ends with a Newline character (invisible). The problem here is that the next character after your last (double) value is not a tab but a line break (Newline).
Simply said, the Scanner tries to extract the values between each delimiter - in your case between tabs. But when the Scanner tries to read the last value in the line, the result value for the last value in the first line (eg) would be look something like this: 0.46EOL *, this is obviously not a double value and result in a InputMismatchException .

The easiest solution to fix the problem would be to remove the leading tabs of each line and append after every last value of a line a tab too.
For example, the first line should look like this: Saint Lucia TAB 179667 TAB 0.46 TAB (replace TAB with an actual tab).

* EOL Newline or 'end of line' character. More Information on Wikipedia .

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