Reputation: 97
I wrote a simple calculator in java, which takes two numbers of type Double from the user and outputs the sum. When I i input the numbers with periods (2.0) I get errors. But when I input with a comma (2,0) it works! It then outputs the answer in the form of 2.0.
Why does my java recognize a double input by comma, but outputs it with a period? The video tutorial I followed, the guy input his double with periods and got it output with periods..
this is my code:
import java.util.Scanner;
public class ScannerIntro {
public static void main(String args[]){
Scanner bucky = new Scanner(System.in);
double firstNumber, secondNumber, answer;
System.out.println("Enter first number: ");
firstNumber = bucky.nextDouble();
System.out.println("Enter Second number: ");
secondNumber = bucky.nextDouble();
answer = firstNumber+secondNumber;
System.out.println("The answer is:");
System.out.println(firstNumber+" + "+secondNumber+" = "+answer);
}
}
Upvotes: 4
Views: 1935
Reputation: 1783
The way the input is interpreted by nextdouble (Class Scanner) depends on the locale you're at:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
In some countries (like France or Germany, a period is used as thousands-separator while the comma is used as decimal Point.
The output is from a different class that uses the default way.
You could either
1) Set the locale for your Scanner so it matches the output. For this use the function:
useLocale(Locale locale)
2) Set the format printf does Format your numbers:
From the docs: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
public PrintStream format(Locale l, String format, Object... args)
Both ways will work. Now you have to decide which is the preferred one for you.
Upvotes: 2