Brady Gareth Brady Gareth - 1 month ago 8x
Java Question

InputMismatchException when trying to use Scanner, what am I missing?

package baker;
import java.util.Scanner;

public class FileReader {

public static void main(String[] args) throws FileNotFoundException {
String name;
double height;
double inches;
double idealWeight;

Scanner fileReader;
fileReader = new Scanner(new FileInputStream("Data/patients.txt"));
while (fileReader.hasNext()) {

name =;
System.out.println("Name: ");
height = fileReader.nextInt();
inches = fileReader.nextInt();

idealWeight = 110 + (height - 5) * 5 + inches * 5;
System.out.println("Ideal Weight: " + idealWeight);


This code throws the following error:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(
at java.util.Scanner.nextInt(
at java.util.Scanner.nextInt(
at baker.FileReader.main(
C:\Users\SFU\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

The last line of the error points to line 22, which is the following line:

height = fileReader.nextInt();

As far as I can tell, there is no reason for the Input mismatch error. Any suggestions? I have posted the file in question (patients.txt) below.

Tom Atto
Eaton Wright
Cary Oki


The reason is because of your name assignment. You do the following:

name =;

The fact is next returns the next token delimited by a space by default. Per the Javadocs:

public String next()

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

So, you can now see that the first and last names can be problematic. For example, if you had this in a file:

John Smith

And you did:;

You would get only John, because it's next complete token and is delimited at the space. That means when you then scan for integers:


The scanner will encounter Smith (a string) and throw an InputMismatchException. Use:

name = fileReader.nextLine();

to receive the whole line instead. This will yield John Smith. Read more about that here.