Why get i InputMismatchException when i use scanner sc.nextDouble()

穿精又带淫゛_ 提交于 2019-12-31 04:36:13

问题


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.



来源:https://stackoverflow.com/questions/30080772/why-get-i-inputmismatchexception-when-i-use-scanner-sc-nextdouble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!