简体   繁体   English

当我使用scanner sc.nextDouble()时为什么会得到InputMismatchException

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

I'd like to read data from a txt file, but I get InputMismatchException when I call nextDouble() method. 我想从txt文件中读取数据,但是当我调用nextDouble()方法时,我得到InputMismatchException Even though I am using the useLocale method, but it doesn't work. 即使我使用useLocale方法,但它不起作用。

The txt file first line is: 1;forname;1.9 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();
        }
    }
}

Blame the French locale: it uses comma as a decimal separator, so 1.9 fails to parse. 归咎于法语区域设置:它使用逗号作为小数分隔符,因此1.9无法解析。

Replacing 1.9 with 1,9 fixes the problem ( demo 1 ). 1,9替换1.9修复了问题( 演示1 )。 If you would like to parse 1.9 , use Locale.US instead of Locale.FRENCH ( demo 2 ). 如果要解析1.9 ,请使用Locale.US而不是Locale.FRENCH演示2 )。

A second problem in your code is the use of \\\\n as the separator. 代码中的第二个问题是使用\\\\n作为分隔符。 You should use a single backslash, otherwise words that contain n would break your parsing logic. 您应该使用单个反斜杠,否则包含n单词将破坏您的解析逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM