I am new to Java and I came up to this error in my program where I can't add the elements in an array of BigDecimal elements. I successfully made it with Integer and Double types but when I change the type to BigDecimal, it won't work at all.
import java.math.*;
import java.util.*;
public class AddBigRealNumbers {
public static void main(String[] args) {
try{
Scanner von = new Scanner(System.in);
System.out.println("Enter the number of figures to be added:");
int numfig;
numfig = von.nextInt();
BigDecimal []nums = new BigDecimal[numfig];
System.out.println("Enter the elements:");
for(int i=0; i<numfig;i++){
nums[i]=von.nextBigDecimal();
}
System.out.println("The elements are: ");
for(int i=0; i<numfig;i++){
System.out.println(nums[i]);
}
BigDecimal sum=BigDecimal.ZERO;
for (BigDecimal i : nums)
sum += i;
System.out.println("The sume of these numbers is:"+sum);
}
catch(Exception e){
System.out.println("Your exception is:" +e);
}
}
}
You can't add BigDecimal with +
, you have to use its add()
function. It is also immutable, so using the same BigDecimal sum for the whole addition won't work.
BigDecimal isn't just another class for numbers like Integer and Double are.