JAVA Write a method that calculates a discount of 20% from the amount of the cus
ID: 3875350 • Letter: J
Question
JAVA
Write a method that calculates a discount of 20% from the amount of the customer who spent most. Only method is needed, no need to write whole code or main method.
public class Customer extends Person implements Comparable<Customer> {
private float totalSpent;
public Customer(String id, String name, float totalSpent) {
super(id, name);
this.totalSpent = totalSpent;
}
public int compareTo(Customer customer) {
int x = this.name.compareTo(customer.name);
if (x == 0) {
return 0;
} else if (x > 0) {
return 1;
} else {
return -1;
}
}
public float getExpenditure() {
return totalSpent;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", totalSpent=" + totalSpent + "]";
}
}
Explanation / Answer
//method which calculates a discount of 20% from the amount of the customer who spent most
public float calculateDiscount(Customer[] customers){
//take first customer from array of all customer
Customer maxSpentCustomer = customers[0];
// find a customer spent most
for (Customer cust:customers){
if (maxSpentCustomer.getExpenditure() < cust.getExpenditure()){
maxSpentCustomer = cust;
}
}
// calulate 20%
return 0.2f * maxSpentCustomer.getExpenditure();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.