1

The .toString() method does work on BigDecimal, but I can't seem to get it to work when I'm looping through an array and referencing it with array[i]. Here's my code, where numb is a string variable:

for (int i = 0; i < b.length; i++) {
    if((b[i].getClass().toString().contains("String") || b[i].getClass().toString().contains("BigDecimal"))&& isNumeric((String)b[i]) && i != b.length-1){ 
        if(!caught){
            caught = true;
            startIndex = i; //where the number starts
            }
            numb+=b[i].toString();

And the error message:

 Exception in thread "main" java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.String

Can someone point me to the right direction?

5 Answers 5

3

The error message is probably due to this cast:

(String)b[i]

Replace it with

b[i].toString()
Sign up to request clarification or add additional context in comments.

Comments

2

b[i] can contain the type BigInteger. You're attempting to cast a type of BigInteger to a String using an explicit cast. This is not possible using this syntax. Instead, if the type is BigInteger, you can convert in the following way:

BigInteger bigInt = new BigInteger("444");
String stringVal = bigInt.toString();

Comments

1

You cannot cast a BigDecimal to a String using an explicit cast, simply because a BigDecimal is not a String.

It depends of how your isNumeric method is implemented* but you have to do :

isNumeric(b[i].toPlainString())

*because toString() can use scientific notation if an exponent is needed.

Comments

1

isNumeric((String)b[i])

Change this as

isNumeric(b[i].toString())

you cannot convert an Object to a String by casting.

Comments

1

you could also try String.valueOf(b[i]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.