Wojciech Kazior Wojciech Kazior - 11 months ago 50
Java Question

Scanner exception while reading different types of variables

I have such a file:


And this is how I try to read it:

InputStream s = Main.class.getResourceAsStream("/file.txt");
Scanner scanner = new Scanner(s);
//Scanner scanner = new Scanner(path); **EDITED**

InputMismatchException is thrown in third line of my code. I know I can use readLine() and parse it to int or double, but it would not work, if my file would look like:

3 0.1

In this situation, the same exception is thrown in the same place.

acm acm
Answer Source

As per your description it looks like a locale problem. As stated by Scanner docs:

An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(java.util.Locale) method. The reset() method will reset the value of the scanner's locale to the initial locale regardless of whether it was previously changed.

I presume your default locale is Polish locale, which decimal separator is a comma. You might want to change your input files to use your locale decimal separator or use a locale which decimal separator is a dot. For example, you could add the following line after the Scanner initialization: