Mat257
Mat257

Reputation: 33

java, input double value by scanner method, number with decimal return error

As a java newbie, I wrote down this code:

import java.util.Scanner;

public class EserciziCap2_6_2 {

    public static void main(String[] args) {
        Scanner aaa = new Scanner (System.in);
        System.out.println("inserire x");
        Double x = aaa.nextDouble();
        System.out.println(x);
    }
}

It works fine with no decimal value like for 4 it returns 4.0, for 2 it returns 2.0 and so on. but , if I type let's say 1.14 it returns below error:

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at EserciziCap2_6_2.main(EserciziCap2_6_2.java:8)

What 's wrong?

Upvotes: 0

Views: 657

Answers (1)

Mesalcode
Mesalcode

Reputation: 140

You have to enter "," instead of ".". If you want to use "." as the comma use:

 public static void main(String[] args) {

    Scanner aaa = new Scanner (System.in);
    System.out.println("inserire x");
    String input = aaa.nextLine().replace(".", ",");
    Double x = Double.parseDouble(input);
    System.out.println(x);
}

Upvotes: 1

Related Questions