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?
The error message is probably due to this cast:
(String)b[i]
Replace it with
b[i].toString()
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.
您也可以尝试String.valueOf(b [i]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.