线程“main”中的异常java.util.InputMismatchException nextDouble()错误?

时间:2016-03-21 11:26:18

标签: java

CitireFisier.java

public class CitireFisier  {
    public static void main(String[] args) {
        File f = new File("fisier.txt");

        Scanner scn = null;
        try {
            scn = new Scanner(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int size = scn.nextInt();  
        System.out.println("val  is " + size);

        double var  = scn.nextDouble();
        System.out.println("val  is " + var);
    }
}

输出

val is 3
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)

fisier.txt

3
0.1 0.7 0.2 init g
0.0 0.0 1.0 g y
0.0 0.0 1.0 g y

nextDouble()收到错误,但0.1为double

2 个答案:

答案 0 :(得分:2)

如果您的语言环境使用逗号作为小数分隔符,则0.1不是双精度数。

要解决此问题,请按如下方式实例化您的扫描仪:

 scn = new Scanner(f).useLocale(Locale.US);

答案 1 :(得分:0)

我猜这些问题取决于所使用的Java版本,因为在我的Java版本(Java(TM)SE运行时环境(版本1.8.0_74-b02))中,我没有收到错误。不过,也许这对您的版本有帮助(如问题评论中所述):

public static void main(String[] args) {
    File f = new File("fisier.txt");
    Scanner scn = null;
    try {
        scn = new Scanner(f);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    int size = scn.nextInt();
    System.out.println("val  is " + size);

    // not needed in my Java Version
    scn.nextLine();

    double var = scn.nextDouble();
    System.out.println("val  is " + var);
}

编辑

您可能还想查看Trouble using nextInt and nextLine()