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