Read numbers using dot as decimal separator

Asked

Viewed 106 times

0

I’m doing an exercise in which I have to take the radius as input value and return the circle area as output.

The code compiles normal without errors, but at the time it will print the value it gives error.

I used the class Locale to accept the entry with point, ex: "2.00". If I type 2.00 input program compiles but gives error if I type 2,00 (comma) or "2" as integer it compiles and prints correctly without errors.

But my intention is to enter values in the US standard (2.00) using values with point, as the international standard says and not with comma as standard "BR".

package exercicio01;

import java.util.Locale;
import java.util.Scanner;
import java.lang.Math;

public class dois {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        Locale.setDefault(Locale.US);

        double r, area, pi = 3.14159;


        System.out.println("Digite o valor do raio:");
        r = sc.nextDouble();


        area = Math.pow(r, 2) * pi;

        System.out.printf("a área do raio  digitado é % .4f \n : ", area);

        sc.close();
    }

}

1 answer

4


No use setting the default locale after creating the scanner, as it was already created with the locale previously set.

Also not a good option to change the default locale (Locale.setDefault), because this change is made for the entire JVM, affecting all applications running on the same JVM.

If you want the scanner to use a specific locale, just do:

Scanner sc = new Scanner(System.in).useLocale(Locale.US);

This way it will read the numbers using the point as decimal separator, independent of the default locale set (and also eliminates the need to use Locale.setDefault).


Another detail is that you should not close the System.in. In the case of a simple exercise like this, it makes no difference, but anyway the tip.

  • so I used one of the tips you suggested, put to start the locale before the scanner, and already solved. In case you close System.in, it is because in the course he taught like this, at least for now, but I will do from now on as you suggested, because I saw that you have good experience.

Browser other questions tagged

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