Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inputting double type numbers with "." returning error. It works with ","

Tags:

java

double

When I input for example firstnum = 1,5; secondnum = 3,2 it returns sum. But when I input numbers with "." instead of "," it returns error.

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextDouble(Unknown Source)
    at Variables.main(Variables.java:11)

Can someone explain me that? In tutorial i watch guy did exacly the same program and it was returning sum even if he used double numbers with ".".

import java.util.Scanner;
public class Variables 
{
    public static void main(String args[])
    {
        Scanner scanny = new Scanner(System.in);
        double first_number, second_number, answer;
        System.out.println("Enter first num: ");
        first_number = scanny.nextDouble();
        System.out.println("Enter second num: ");
        second_number = scanny.nextDouble();
        answer = first_number + second_number;
        System.out.println(answer);

    }

}
like image 260
Bartosz Sobczyński Avatar asked Dec 08 '22 06:12

Bartosz Sobczyński


1 Answers

It's Locale/i18n, your machine and his machine has different locales. The JVM use your system locale as default. To change you can do:

Locale.setDefault(new Locale("pt", "BR"));

In this case, your decimal separator will be ","

If you set locale to:

Locale.setDefault(Locale.ENGLISH);

Then you need to use "."

You can read more about internationalization/i18n on http://docs.oracle.com/javase/tutorial/i18n/

like image 116
Henrique dos Santos Goulart Avatar answered May 20 '23 14:05

Henrique dos Santos Goulart