这是我尝试将Fruit类中的isCompatibleWith()添加到名为ShoppingCard的类中,并在其中添加addFruit的地方。
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;
}
答案 0 :(得分:0)
方法定义为:
public boolean isCompatibleWith(Fruit other)
static
:
Fruit
类本身而不是Fruit
类的实例中调用它Fruit
类型的参数:
Fruit
实例以与调用该方法的实例进行比较从类内部(如您的代码中),从该类的另一个非静态方法中,您将其命名为
boolean res = this.isCompatibleWith(otherFruit);
// or easier :
boolean res = isCompatibleWith(otherFruit);
从该类中移除
Fruit f1 = new Fruit();
Fruit f2 = new Fruit();
boolean res = f1.isCompatibleWith(f2);
因此,您需要在您的方法中使用其他参数创建一个新的Fruit
,然后执行代码:
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;
}
布尔提示
if(condition == false)
==> if(!condition)
if(condition == true)
==> if(condition)