LaVOZs

The World’s Largest Online Community for Developers

'; java - Returning the cheapest item - LavOzs.Com

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){ 

    }

}

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
   }
}

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.

Related
Return multiple values to a method caller
Accessor and Mutator Methods confusion
OGNL setValue target is null
Java Inventory Program problems
Method override returns null
Shopping Cart using two files (class and main method) Java
Hibernate : Why FetchType.LAZY-annotated collection property eagerly loading?
JavaFX: update tableview context by selected combobox(binding)
How to implement parcelable with my custom class containing Hashmap and SparseArray?