Home > Blockchain >  JAVA CALCULATOR Exception in thread "main" java.util.InputMismatchException
JAVA CALCULATOR Exception in thread "main" java.util.InputMismatchException

Time:10-09

Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:943)
    at java.base/java.util.Scanner.next(Scanner.java:1598)
    at java.base/java.util.Scanner.nextDouble(Scanner.java:2569)
    at testCalculator.main(testCalculator.java:12)

I'm trying to make a working calculator, which reads even decimal numbers, but it doesn't work. At the start it was integer valid only calculator, but within 30 minutes i tried to change it. Sadly my efforts were for nothing, anybody can help me with it? How to improve this calculator, so it can take decimal numbers without errors. Thank you very much for every answer!

import java.util.Scanner;

public class testCalculator {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);

    while(true){
        System.out.println("First Number");
        double x = read.nextDouble();
        read.nextLine();
        System.out.println("Second Number");
        double y = read.nextDouble();
        read.nextLine();
        System.out.println("What you want to do?   / * - ");
        String z = read.nextLine();

        switch(z){
            case " ":
                System.out.println(x   y);
                break;
            case "-":
                System.out.println(x - y);
                break;

            case "*":
                System.out.println(x * y);
                break;

            case "/":
                System.out.println (x / y);
                break;
            default:
               System.out.println("bruh");
               break;

        }
    }

}

CodePudding user response:

Given the locale info (pl_PL) the decimal separator is a comma, e.g. 21,15.

To discover such things add the line

System.out.println(java.util.Locale.getDefault());

Use the supported locales to look it up:

https://www.oracle.com/java/technologies/javase/jdk8-jre8-suported-locales.html

And get further info on the locale:

https://www.localeplanet.com/icu/pl-PL/index.html

and reference the "Decimal separator" value: ,.

  •  Tags:  
  • java
  • Related