当我用逗号或小数点分隔小数时,扫描会翻倍

问题描述:

我是Java的新手,当时我在做一个简单的计算器。问题是,当我输入的数字是 3.1时,它会给出异常错误,但是在写 3,1时,它就可以了。

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.

我的朋友,但是,它有一个更高级的计算器(带有字符串解析),当我运行他的代码时,情况恰恰相反:3,1给出了异常错误,3.1可以正常工作。

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我很想知道是什么原因导致了这些不同的行为。

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();
    }

}

最终编辑:他确实使用 Double.parseDouble()。知道了,区别确实在于它的本地化。本来应该寻找它,但之前从未听说过这个概念。

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.

谢谢

因为您使用的是差异 Local 可以用一个点扫描它。和另一个用逗号,$ c扫描$ c>修复它,您应该像这样修复您的扫描仪:

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);

例如:


  • 如果您使用的是 Local.US ,则应使用扫描双精度。
    6.6

  • 如果您使用的是 Locale.FRENCH ,您应使用
    a 扫描您的双精度,如 6,6

  • 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