Home > Blockchain >  Building code for counting the number of decimal places in Java
Building code for counting the number of decimal places in Java

Time:10-09

I am now trying to build a source code for counting the number of decimal places of floating point value input by the user.

Below is my code written in Java:

import java.util.Scanner;
import java.lang.Math;

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

        double double1 = input.nextDouble();
        int int1 = (int) double1;
        String string1 = Double.toString(double1), string2 = Integer.toString(int1);
        int string2Size = string2.length()   1, string1Size = string1.length() - string2Size;

        System.out.println("Here we know that the number of  decimal places that you input is "   string1Size);
    }
}

And it results in the following error message:

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 CountDecimalPlaces.main(CountDecimalPlaces.java:8)

Note that this error message occurs after I enter a floating-point input, not when I am trying to run the source code. What's wrong?

CodePudding user response:

There's a simple cause for your problem, but, your code as written is more fundamentally just entirely broken.

The immediate problem

A Scanner has a locale - a configuration about the ways things are entered in the language/country that you configured in your OS. Your OS is configured to use a comma and not a dot. Either call scanner.useLocale(Locale.ENGLISH) to change this locale, or, enter numbers with commas instead.

But.. nevermind. This code does not work and never will

double doesn't store numbers the way you think it does. For example, 0.3? That's not a double. It simply isn't. Computers aren't magical; there are an infinite amount of numbers between 0 and 1, and double can represent a lot more than just a number between 0 and 1. Computers aren't magical; they don't have infinite room to store this stuff. It can't even store 0.3. Computers are binary, too. They use binary counting, not decimal counting, so the question 'how many digits does it have' (which implies: "... in decimal") is entirely foreign to a computer, which counts in binary and not decimal.

BigDecimal is a class that can do it. I highly doubt this homework involves having to do that. Point is, for many, many numbers, this code will not work and nothing can be done to make it work, other than to get rid of almost all of it, and use BigDecimal instead, which is well beyond the level of this homework.

I think the only valid conclusion is that whatever you got this exercise from, it's undoable.

  • Related