Scanning doubles when I separate decimals with comma or dot

假如想象 提交于 2020-02-25 00:26:48

问题


I'm rather new to Java and I was making a simple calculator. Problem is when I my input number is for example "3.1" it gives an exception error, but when writing "3,1" it works just fine.

My friend, however, has a slightly more advanced calculator (with string parsing) and when I run his code the opposite happens: 3,1 gives exception error, 3.1 works perfectly.

I was looking forward to know what causes these different behaviors.

I made this simple sum just now and the same happens, I'll edit and put his calculator code in a few minutes

import java.util.Scanner;

public class Tutorial_7 {
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        double num1, num2;

        System.out.println("Introduza os dois números");

        System.out.println("1º: ");
        num1 = scan.nextDouble();
        System.out.println("2º: ");
        num2 = scan.nextDouble();

        System.out.println((num1 + num2));
        scan.close();
    }

}

Final edit: He does use Double.parseDouble(). Got it, the difference is indeed in where it is localized. Should have looked for it but never heard of this concept before.

Thank you


回答1:


Because you are using difference Local for that one can scan it with a dot . and another with a comma , to fix it you should to fix one for your Scanner like this :

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

For example:

  • If you are using Local.US you should to scan your double with a . like 6.6
  • If you are using Locale.FRENCH you should to scan your double with a , like 6,6


来源:https://stackoverflow.com/questions/42332273/scanning-doubles-when-i-separate-decimals-with-comma-or-dot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!