Question

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?

Était-ce utile?

La solution

The error message is probably due to this cast:

(String)b[i]

Replace it with

b[i].toString()

Autres conseils

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();

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.

isNumeric((String)b[i])

Change this as

isNumeric(b[i].toString())

you cannot convert an Object to a String by casting.

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top