简体   繁体   中英

Period in output double but comma in input double?

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

    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM