Input mismatch when reading double from file

淺唱寂寞╮ 提交于 2019-12-02 07:04:12

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!