Reputation: 5
I am pretty new to Java, but what I am currenlty stuck is I am trying to return an item but it will return the cheapest item. In the book I am using, it says I have to "Add a method cheaper which takes another StoreItem. It returns whichever item is cheaper, this item or the one passed in.", I am just confused on how you get it to return the cheapest item.
package cwk18;
import java.util.Collections;
public class StoreItem {
private String name;
private double price;
public StoreItem(){ // constructor
name= "name unavailable";
price = 1;
}
public StoreItem(String naming1,int val){ // parameterized construtor
this();
setName(naming1);
setPrice(val);
}
public String getName(){ //name accessor
return this.name;
}
public void setName(String newName){ // name mutator
this.name = newName;
}
public double getPrice(){ // price accessor
return this.price;
}
public void setPrice(int val){// price mutator
this.price = val;
}
public void cheaper(StoreItem newItem){
}
}
Upvotes: 0
Views: 206
Reputation: 122
If you say this function is to return whichever item is cheaper.
The function shouldn't be void
but 'The object name'
public StoreItem cheaper(StoreItem newItem) \\before is public void cheaper(...
{
if(this.price >newItem.getPrice())
{
return newItem;
}
else
{
return this; //this means return the current item
}
}
Upvotes: 1
Reputation: 40034
First, you need to change your return type from:
public void cheaper(StoreItem newItem){
}
to
public StoreItem cheaper(StoreItem newItem){
}
Now you just need to use an if statement
to compare prices of the StoreItem
passed as newItem
to the one that this class represents.
Upvotes: 0