-->

Why get i InputMismatchException when i use scanne

2019-02-28 02:59发布

问题:

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();
        }
    }
}

回答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.