0

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...

4
  • 1
    Please, post this error. Commented Sep 20, 2012 at 16:58
  • 2
    Could we also see how you declare your inputFile object (I assume it's a Scanner?) as well as some samples from the file itself? Commented Sep 20, 2012 at 16:59
  • 1
    What type is input file? Is it expecting binary or text encoding? Commented Sep 20, 2012 at 16:59
  • You have the wrong constructor for file Scanner. See my update below. :) Commented Sep 20, 2012 at 21:38

2 Answers 2

1

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.


Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

@iccthedral Correct. Think I should add it in to the answer as another example?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.