Using
double variable = inputFile.nextDouble();
Gives the mismatch error and I can't figure out why... Anyone know what's up?
The input file is just a bunch of doubles like 5.0...
Okay here is the code snippet
String fileName;
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter file name that contains the matrix and vector: ");
fileName = scanner.nextLine();
Scanner inputFile = new Scanner(fileName);
double a1 = inputFile.nextDouble();
the input file is a plain text document .txt in this format
5.0 4.0 -3.0
4.0 2.0 5.0
6.0 5.0 -2.0
-13.0 4.0 12.0
I don't understand why it wouldn't take those as doubles...
As far as what its expecting the format of the file to be... I suppose binary? isn't that the default? I didn't specify in the code...
Add a check beforehand
if (inputFile.hasNextDouble()) {
double variable = inputFile.nextDouble();
} else if (inputFile.hasNext()) {
System.out.println("Not double at token " + inputFile.next());
}
in order to identify why and where exactly it fails.
It could be that your delimiter isn't " "
and that you haven't specified it manually. To set the delimiter, call one of useDelimiter(...)
functions.
InputMismatchException
is the result of a scanner attempting to parse a string into a format to which it cannot to parsed. For example, calling Double.parseDouble
on a string such as "3.3 meters" will throw a NumberFormatException. As iccthedral added, even a string as nontrivial as "3.0 " (notice the whitespace) will result in an NFE.
When a NumberFormatException occurs in Scanner.nextDouble()
, the NFE is wrapped and rethrown in an InputMismatchException, which is what is occuring here.
To ensure that your Scanner can read a double, call Scanner#hasNextDouble()
and only proceed to acquire the double if the scanner has that next double.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.