My task is as follows:
- Create a Java class called
SalesPerson
with following properties:
sales id - data typeint
sales amount - data typedouble
- Write a default constructor to initialize each of the properties.
- Code getters and setters for each property.
- In the main method, instantiate two instances of
SalesPerson
type. - Using setters, set the id and sales amount for each sales person. Then compare each sales person's sales amount and display the id of the sales person with higher sales amount.
I believe I have correctly written everything so far but I am at a loss for how to compare "amount1" and "amount2". The instructions I was given are pasted above if that helps at all. My current code is this:
public class SalesPerson {
public int salesId;
public double salesAmount;
public SalesPerson() {
salesId = 101;
salesAmount = 1002.36;
}
public void setSalesId(int i) {
salesId = i;
}
public void setSalesAmount(double a) {
salesAmount = a;
}
public int getSalesId() {
return salesId;
}
public double getSalesAmount() {
return salesAmount;
}
public static void main(String[] args) {
SalesPerson amount1 = new SalesPerson();
SalesPerson amount2 = new SalesPerson();
System.out.println("ID is: " amount1.getSalesId());
System.out.println("Sale amount is: " amount1.getSalesAmount());
amount2.setSalesId(254);
amount2.setSalesAmount(1563.58);
System.out.println("ID is: " amount2.getSalesId());
System.out.println("Sale amount is: " amount2.getSalesAmount());
if(amount2 > amount1) {
}
}
}
CodePudding user response:
You have to campare getter getSalesAmount()
of amount1
and amount2
but you compare whole object.
if(amount2.getSalesAmount() > amount1.getSalesAmount()) {
System.out.println("Id: " amount2.getSalesId());
}
else {
System.out.println("Id: " amount1.getSalesId());
}
CodePudding user response:
You could write your code like that, but in order to compare to instances of the same class, that class must implement the Comparable interface. See here https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html. After doing so you will be able to store SalesPerson objects in sorted structures like TreeSet or TreeMap if need be.