How to read a float with Scanner

My problem is as follows:

package com.vreawillsaveyou01;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        float number = scanner.nextFloat();
        System.out.println(number);
    }
}

When I type a floating point number, using the point as a decimal separator (for example, 3.92), the program gives the following error:

Exception in thread "main" java.util.InputMismatchException
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextFloat(Scanner.java:2496)
at com.vreawillsaveyou01.Main.main(Main.java:8)

What am I doing wrong and how can I correct it?

Author: Maniero, 2019-07-16

1 answers

The format of a float recognized by Scanner (including the decimal separator) depends on the Locale that he's using.

If you do not specify any locale , the default that is configured in the JVM is used (which you can query which is by calling the method Locale.getDefault()).

On my machine, for example, the default is pt_BR (Brazilian Portuguese), and the decimal separator is the comma (so this code only works if I type, for example, 3,92).


In the case, for the format that uses the period as a decimal separator, just use a locale that uses this setting. One option is the constant predefined for American English :

Scanner scanner = new Scanner(System.in);
scanner.useLocale(Locale.US); // setar o locale
float number = scanner.nextFloat();
System.out.println(number);

With this, you can type 3.92 that the number will be read correctly(but now 3,92 no longer works).

 2
Author: hkotsubo, 2019-07-16 21:36:04