3

im trying to read a integer and two doubles from a text file. I wrote a shorter example demo of my problem.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        int q = 0;
        double w = 0, e = 0;
        Scanner s = null;
        try {
            s = new Scanner(new File(args[0]));
            while(s.hasNext()) {
                q = s.nextInt();
                w = s.nextDouble();
                e = s.nextDouble();
            }
            System.out.println("1: " + q + "\n2: " + w + "\n3: " + e);
        } catch(FileNotFoundException e1) {
            e1.printStackTrace();
            System.out.println(e1.getMessage());
        } finally {
            if(s != null) {
                s.close();
            }
        }
    }
}

It gives me a

    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 Test.main(Test.java:14)

I think my Scanner got a problem with reading the double, but I can't figure out why.

My text file contains:

    3000 30.3 10.4
koin
  • 203
  • 2
  • 12
  • have you tried possibly casting the value? So for example putting w = (double) s.nextDouble(); – Bryan Herrera Jan 10 '16 at 01:53
  • @BryanHerrera `Scanner.nextDouble` should simply return `double`. There is no need to cast. And even if it didn't return `double`, that would result in a compiler warning because of assigning an invalid type to a variable, not a runtime exception. – Arc676 Jan 10 '16 at 01:55
  • s.useLocal(Locale.US); fixed it for me. Since Java works with dots I never thought of this :/ Guess the default Local for me was Germany then. – koin Jan 10 '16 at 01:57
  • The file has the numbers stored in the form of strings. So first use the substring method using space as a delimiter to get each value, then cast to integer double or whatever using the methods from the String library. – SeahawksRdaBest Jan 10 '16 at 01:58
  • @koin Just out of curiosity, what's the Locale for? does that have to change per country or something? – Bryan Herrera Jan 10 '16 at 01:59
  • @BryanHerrera I think in most European states they use the comma as a decimal separator, and my text file contained dots. So Locale.US fixed it :) – koin Jan 10 '16 at 02:14
  • @BryanHerrera In some European countries (such as Italy and possibly Germany) every third digit is separated by a period and decimals are separated by commas. In English, the reverse applies. The `Scanner` was using the wrong locale, so it was looking for commas as delimiters for decimals. koin: you can answer your own question to show that the problem is solved – Arc676 Jan 10 '16 at 02:15
  • @Arc676 Oh I see, thanks for the info! – Bryan Herrera Jan 11 '16 at 01:08

0 Answers0