This code have no syntax error, but gets InputMismatchException when I put the float value. Double value instead float gets the same exception. If I enter every value in F.f format (with a dot) the exception appears. If I enter with 1,9 value (comma) this code works. Why?
Scanner l = new Scanner(System.in);
String n;
int i;
float a;
System.out.print("N: ");
n = l.nextLine();
System.out.print("I: ");
i = l.nextInt();
System.out.print("A: ");
a = l.nextFloat();
System.out.println(n);
System.out.println(i);
System.out.println(a);
Thanks in advance!
The javadoc explains that the Scanner
methods default to using the default Locale's formatting rules when reading numbers.
It says:
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(Locale.Category.FORMAT)
method; it may be changed via theuseLocale(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.
So ... if you want to get your program to recognize 1.9
rather than 1,9
, either change your default locale (within the program, in the launch parameters, or in the system settings) ... or configure the Scanner
with the appropriate Locale
, as described.