maen maen - 25 days ago 17
Java Question

Scanner InputMismatchException from file

Doing my first steps with Java, here's my problem:

1.) the

rawData.txt
can be read:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import static java.lang.System.out;

class ReadAndWrite {

public static void main(String args[])
throws FileNotFoundException {

Scanner diskScanner = new Scanner(new File("rawData.txt"));
String diskString;
diskString = diskScanner.nextLine();
out.println(diskString);
diskScanner.close();
}
}


The result in eclipse console is :

>19.5 5


So I guess the content can be read.

But:
nextDouble()
and
nextInt()
won't work:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

class ReadAndWrite {

public static void main(String args[])
throws FileNotFoundException {

Scanner diskScanner = new Scanner(new File("rawData.txt"));
double unitPrice, quantity;
unitPrice = diskScanner.nextDouble();
quantity = diskScanner.nextInt();

[...]

diskScanner.close();

}
}


The error message from console is:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at ReadAndWrite.main(ReadAndWrite.java:16)


So what can I do to understand the problem?

Answer

From javadoc regarding the exception :

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

If you are pretty sure about the data type to be read, you can use the specific methods. otherwise go for the .next() method. that returns the String

And if you want to do calculations over the values, you can parse that strings using the parsers like Double.valueOf("5.2") or Integer.valueOf("5") and handling the parse exceptions in try catch blocks.

Comments