1

我想从txt文件中读取数据,但是InputMismatchException当我调用nextDouble()方法时我得到了。即使我正在使用该useLocale方法,但它不起作用。

txt文件第一行是: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();
        }
    }
}
4

1 回答 1

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.

于 2015-05-06T15:16:52.923 回答