How to read a float with Scanner

Asked

Viewed 1,484 times

1

My problem is this:

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 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 I’m doing wrong and how can I fix it?

  • the code seems correct, is typing the number with semicolon?

  • I’m typing with dot

  • @Ricardopunctual for example when I put 3.92 gives me that mistake

1 answer

3


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

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

In 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 this case, for the format that uses the dot as decimal separator, just use a locale use this setting. One option is to preset constant 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 doesn’t work anymore).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.