I'm trying to write a program to determine if the input value is irrational or not by determining the number of digits. why won't it compile?

470 views Asked by At

If the number of digits is infinite then I mark it as irrational and everything else is rational as it would be finite.

I tired input 3.14 but it crashed and didn't compile the output of irrational or rational.

import java.math.BigDecimal;

import java.util.Scanner;

public class non_terminating_decimals {
    public static void main(String[] args) {

        Scanner inputNumber = new Scanner(System.in);
        System.out.println("input number : ");
        BigDecimal inputnumber = inputNumber.nextBigDecimal();
        BigDecimal numerofDigits = input(new BigDecimal(String.valueOf(inputnumber)));

        BigDecimal infinity = BigDecimal.valueOf(Double.POSITIVE_INFINITY);

        if (numerofDigits == infinity) {

            System.out.println("Irrational");
        }
        else {

            System.out.println("Rational");
        }
    }

    static int integerDigits(BigDecimal number) {
        return number.signum() == 0 ? 1 : number.precision() - number.scale();
    }

    static BigDecimal input(BigDecimal number) {
        return BigDecimal.valueOf(0);
    }
}
1

There are 1 answers

2
access violation On

Let's unpack this statement:

BigDecimal infinity = 
    BigDecimal.valueOf(Double.POSITIVE_INFINITY);

Double.POSITIVE_INFINITY is some number.

Looking at the documentation for BigDecimal.valueOf, we see it uses Double.toString() to do the conversion.

Looking at the documentation for that, we see that a value of positive infinity results in the string "Infinity".

Thus, we're effectively left with trying to evaluate

BigDecimal("Infinity");

And if we look at the documentation for that particular constructor, there's no suggestion it can handle non-numeric string arguments.