Derek Derek - 1 month ago 7
Java Question

Input mismatch when reading double from file

I have to write a program that will read the names and balances from text file "balances.txt" and organize into a report that will then sum up the balances into a total. This is what the file contains:

JAKIE JOHNSON,2051.59
SAMUEL PAUL SMITH,10842.23
ELISE ELLISON,720.54


I had originally written the code which gave me exactly what I wanted, but was told not use loops, arrays, or
parseDouble
. I've now tried the following, but I keep getting an error every time I used
nextDouble
. The code:

import java.io.File;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.io.FileInputStream ;
import java.io.FileNotFoundException ;
import java.io.IOException ;
import java.util.Scanner ;

public class BankFile {
public static void main(String[] args) throws IOException {
Scanner fileIn = null;

try {
String filename = "balances.txt" ;
File newFile = new File(filename);
Scanner in = new Scanner(newFile);

in.useDelimiter(",");

String name = in.next();
System.out.println(name);
// trying to see if first name will display

double money = in.nextDouble();
System.out.println(money);
// trying to see if first double will display
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
}
}


This is the output and exception stacktrace:

JAKIE JOHNSON
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 Lab2.main(BankFile.java:52) `

Answer

If you take a look at the Javadoc:

useDelimiter

public Scanner useDelimiter(String pattern)

Sets this scanner's delimiting pattern to a pattern constructed from the specified String.

Now if you take a look at how you do yours:

in.useDelimiter(",");

This will use commas as the delimiter, now let's take a look at your text file:

JAKIE JOHNSON,2051.59
SAMUEL PAUL SMITH,10842.23
ELISE ELLISON,720.54

At first it may seem that commas are fine, but since you've set the delimiter, this is what happens:

First you call in.next() which returns:

JAKIE JOHNSON,2051.59
^^^^^^^^^^^^^

That's fine, but when you then call in.nextDouble(), the below happens:

JAKIE JOHNSON,2051.59
              ^^^^^^^
SAMUEL PAUL SMITH,10842.23
^^^^^^^^^^^^^^^^^

As you can see, the next line is also selected along with the double, which isn't a valid double. This causes Java to report an InputMismatchException, as the expected input isn't what you get - a string. To combat this, use a regular expression to also delimit newlines:

in.useDelimiter(",|\n");

This will match new-lines and commas, so it will delimit correctly. The pipe (|) means that it will delimit either. This will correctly output:

JAKIE JOHNSON
2051.59