I am running into a very simple problem that is driving me insane. I am trying to calculate the commission of sales and add it to the a salary but when I run the code it always gives me a commission of $0 and a compensation of $0. Here is my code I have so far:
package compensationcalculator;
import java.text.NumberFormat;
public class CompensationCalculator {
private double salary = 75000;
private double sales;
private double commission;
private double compensation;
public CompensationCalculator() {
this.salary = 75000.00;
}
public void setSales(double sales) {
this.sales = sales;
}
public double getCommission() {
this.commission = (sales * 0.2);
return commission;
}
public double getCompensation() {
this.compensation = (salary + commission);
return compensation;
}
public String toString() {
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return ("Annual Salary: " + fmt.format(salary) + "\n"
+ "Total Sales: " + fmt.format(sales) + "\n"
+ "Total Commission: " + fmt.format(commission) + "\n"
+ "Total Annual Compensation: " + fmt.format(compensation));
}
}
Now when I enter 5000 when prompted for the sales I get this as an answer after it runs:
Annual Salary: $75,000.00
Total Sales: $5,000.00
Total Commission: $0.00
Total Annual Compensation: $0.00
I am sure this is a simple error, but I have not used Java in quite some time. I have compared it to some of my really old code from years ago and can't see what I am missing. Any guidance would be very welcome!
The compensation value is based on the commission, which is a calculated value.
You either need to pre-calculate all the values when you set the values or you need to use the values from these methods, for example...
public void setSales(double sales) {
this.sales = sales;
commission = sales * 0.2;
compensation = salary + commission;
}
public double getCommission() {
return commission;
}
public double getCompensation() {
return compensation;
}
public double getCompensation() {
this.compensation = (salary + getCommission());
return compensation;
}
public String toString() {
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return ("Annual Salary: " + fmt.format(salary) + "\n"
+ "Total Sales: " + fmt.format(sales) + "\n"
+ "Total Commission: " + fmt.format(getCommission()) + "\n"
+ "Total Annual Compensation: " + fmt.format(getCompensation()));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With