0

This is where I am trying to add isCompatibleWith() from the class Fruit into a class called ShoppingCard and specifcaly addFruit within it.

  public boolean addFruit(String fruitName,int type, int numItems, int itemWeight) {
     if (toCapacity() == false)
     {
         if (Fruit.isCompatibleWith() == true) //This line does not work.
         {

             return true;
         }
         else
             System.out.println("Cannot add fruit, incompatible with other fruits.");     
     }
     else
         System.out.println("Cannot add fruit, cart is full.");
     return false;}

Fruit.java

    public boolean isCompatibleWith(Fruit other) {
    if (!this.isPerishable() && !other.isPerishable()) // both are non perishable
        return true;
    if (this.isPerishable() != other.isPerishable()) // one is perishable, the other is not
        return false;
    if (this.getType() == other.getType()) // if you've gotten here, both are perishable
        return true;
    return false;
}
  • 1
    You need to call `isCompatibleWith()` on an instance of `Fruit`, and pass it another instance of `Fruit`. E.g. `fruit1.isCompatibleWith(fruit2)`. Calling it without any specific fruits doesn't make any sense. – khelwood Dec 15 '18 at 20:08
  • Can you share the constructor of Fruit ? – azro Dec 15 '18 at 20:16
  • 1
    Possible duplicate of https://stackoverflow.com/q/285177/10424104 – Lloyd Nicholson Dec 15 '18 at 21:23

1 Answers1

0

Method definition is :

public boolean isCompatibleWith(Fruit other)
  • is not static :
    • so you need to call it from an instance of Fruit not from Fruit class itself
  • has one parameter of type Fruit :
    • so you need to pass an instance of Fruit to be compared with the one which call the method

  1. From inside the class (like on your code), from another non-static method of the class, you'll call it like

    boolean res = this.isCompatibleWith(otherFruit);
    // or easier : 
    boolean res = isCompatibleWith(otherFruit);
    
  2. From oustide the class it'll look like

    Fruit f1 = new Fruit();
    Fruit f2 = new Fruit();
    boolean res = f1.isCompatibleWith(f2);
    

So you need in your method, to create an new Fruit with the other parameter and then execute your code :

public boolean addFruit(String fruitName,int type, int numItems, int itemWeight) {
    if (!toCapacity()){
        // change to match your constructor
        Fruit other = new Fruit(fruitName, type, numItems, itemWeight);    
        if (isCompatibleWith(other)){
            //Implement your logic to 'add' the fruit somewhere
            return true;
        }else{
            System.out.println("Cannot add fruit, incompatible with other fruits."); 
        }    
    }else{
         System.out.println("Cannot add fruit, cart is full.");
    }
    return false;
}

Tips for boolean

  • if(condition == false) ==> if(!condition)
  • if(condition == true) ==> if(condition)
azro
  • 53,056
  • 7
  • 34
  • 70