问题
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.
like6.6
- If you are using
Locale.FRENCH
you should to scan your double with a,
like6,6
来源:https://stackoverflow.com/questions/42332273/scanning-doubles-when-i-separate-decimals-with-comma-or-dot