0

I get java.util.inputmismatchexception when using nextDouble() on a file containing only doubles. Here is the relevant section of code:

public static double[] getGravity() throws IOException
{
    Scanner file = new Scanner("SurfaceGravity.txt");
    double[] gravity = new double[8];
    for(int index = 0; index < gravity.length; index++)
        gravity[index] = file.nextDouble();  //Here is where I get the error
    file.close();
    return gravity;
}

And here is the contents of SurfaceGravity.txt

3.700465457603474
8.8661999605471
9.8
3.697967684866716
24.776754466506414
10.43814587026926
8.861473215210253
11.131680688084042
0.6128071987535232

I was under the impression that inputmismatchexception occurs when the token is the wrong type but as far as I can tell all of the tokens in the file are doubles so I am a bit confused.

2 Answers2

0

There is no double value in String SurfaceGravity.txt. You probably want new Scanner(new File("SurfaceGravity.txt"))

See javadoc for Scanner(String):

Constructs a new Scanner that produces values scanned from the specified string.

And Scanner(File)

Constructs a new Scanner that produces values scanned from the specified file.

Bedla
  • 4,789
  • 2
  • 13
  • 27
0

The example you gave you haven't initialised the File you want to read from.

There are also a couple of issues with the implementation: Say for instance that the number of items within the file were to change then you'd have to change your implementation, as at the moment you are limited to 8 values.

public static List<Double> getGravity() throws IOException{
    File file = new File("SurfaceGravity.txt");
    Scanner input = new Scanner(file);

    List<Double> list = new ArrayList<>();
    while(input.hasNextDouble()){
        list.add(input.nextDouble());
    }
    return list;
}

Note: It is possible to use a double[] if absolutely necessary, but for that you'd need to find out the number of lines in the file.

Luke Garrigan
  • 4,571
  • 1
  • 21
  • 29