1

I'd like to read data from a txt file, but I get InputMismatchException when I call nextDouble() method. Even though I am using the useLocale method, but it doesn't work.

The txt file first line is: 1;forname;1.9

public class SimpleFileReader {
    public static void main(String[] args){
        readFromFile();
    }
    public static void readFromFile(){
        try {
            int x = 0;
            File file = new File("read.txt");
            Scanner sc = new Scanner(file).useDelimiter(";|\\n");
            sc.useLocale(Locale.FRENCH);
            while (sc.hasNext()){
                System.out.println(sc.nextInt()+" "+sc.next()+" "+sc.nextDouble());
                x++;
            }
            System.out.println("lines: "+x);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Bbeni
  • 75
  • 8

1 Answers1

1

Blame the French locale: it uses comma as a decimal separator, so 1.9 fails to parse.

Replacing 1.9 with 1,9 fixes the problem (demo 1). If you would like to parse 1.9, use Locale.US instead of Locale.FRENCH (demo 2).

A second problem in your code is the use of \\n as the separator. You should use a single backslash, otherwise words that contain n would break your parsing logic.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I'd like to use a decimal point instead of a comma and i've rewritten this code useLocale(Locale.US) and i tried Locale.ENGLISH , but none of them work. – Bbeni May 06 '15 at 15:26
  • @Bbeni It's a different problem - you get an exception on a line that has an `n`. Please see the edit. – Sergey Kalinichenko May 06 '15 at 15:34
  • The txt file was wrong. I had to replace the end of line characters from \r to \n. It's working now. Thank you for help – Bbeni May 06 '15 at 15:40