I keep getting the
The method add(BigDecimal) in the type BigDecimal is not applicable for the arguments (pay)"
error with the code below.
For reference I have saved the pay
class in a separate file, where I import BigDecimal
as well.
Would one of you like to point out where I'm lacking/misunderstanding? I've tried to find a solution, but I couldn't find something.
import java.util.Scanner;
import java.math.BigDecimal;
class SalesPreInt {
public static void main(String[] args) {
Pay pay = new Pay();
pay.basePay();
BigDecimal intCalc = new BigDecimal("0.15");
Scanner userInput = new Scanner(System.in);
System.out.println("What were your total sales?");
BigDecimal salesPre = userInput.nextBigDecimal();
System.out.println("You're Total Sales were "+salesPre);
userInput.close();
BigDecimal postIntCalc = salesPre.multiply(intCalc);
BigDecimal salesCom = postIntCalc.add(salesPre);
int finalCalc = salesCom.add(pay);
System.out.println("Your total sales including commission is "+salesCom);
System.out.println("Your total pay is"+finalCalc);
}
}
pay.java file below:
import java.math.BigDecimal;
public class Pay {
public void basePay() {
int basePay = 50000;
BigDecimal bd = new BigDecimal(String.valueOf(basePay));
}
}
Like the error message tells you, the add
method of BigDecimal
with one argument expects a BigDecimal
instance: [javaDoc]
public BigDecimal add(BigDecimal augend)
Returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).
Parameters:
augend - value to be added to this BigDecimal.Returns:
this + augend
You've passed a variable of type Pay
to this method and since Pay
is not a subtype of BigDecimal
it is not related to it. The method add
can't know how to add a Pay
instance, the compiler complains about that argument type.
You can do the following fix, to bypass that problem:
Your basePay
method creates a BigDecimal
and I guess this is the one you like to add to salesCom
, so change that method a bit:
public BigDecimal basePay() {
int basePay = 50000;
return new BigDecimal(String.valueOf(basePay));
}
This method now creates a BigDecimal
and returns it to the calling method. Now change the add
method call to use the basePay
method:
int finalCalc = salesCom.add(pay.basePay());
Now there is only one problem left. As you can see in the JavaDoc posted above, add
returns a new BigDecimal
instance, but you're assigning the returned value to the variable finalCalc
, which is of type int
. So we need to change it to BigDecimal
:
BigDecimal finalCalc = salesCom.add(pay.basePay());
Now your code compiles and it should work as expected.