0

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

Output

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() receive the error but 0.1 is double!

Mr. Polywhirl
  • 31,606
  • 11
  • 65
  • 114
dany
  • 11
  • 5

2 Answers2

2

If your locale uses comma as the decimal separator, then 0.1 is not a double.

To fix this, instantiate your Scanner like so:

 scn = new Scanner(f).useLocale(Locale.US);
RafToTheK
  • 86
  • 4
0

I guess the problems depends on the Java version used, because in my Java Version (Java(TM) SE Runtime Environment (build 1.8.0_74-b02)), I don't get the error. Nevertheless, maybe this helps for your version (as mentioned in the question's comments):

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

EDIT:

You may also want to look at Trouble using nextInt and nextLine()

Community
  • 1
  • 1
Philipp
  • 1,129
  • 1
  • 13
  • 32