4

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

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Fosh
  • 123
  • 1
  • 2
  • 9
  • 2
    Without knowing what the code looks like for either of these implementations, we cannot possibly answer. Sorry. – Joe C Feb 19 '17 at 20:08
  • 2
    Read the documentation of Scanner.nextDouble(): it says what it does. Read the documentation of Double.parseDouble() (that your friend probably uses): it says what it does. One is localized, the other isn't, and it's all documented in the javadoc. – JB Nizet Feb 19 '17 at 20:10

1 Answers1

7

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140