对于类型(对象),该方法未定义

时间:2016-10-28 18:52:50

标签: java

我有三个对象,每个对象都分配了一个单独的整数。

Food hamburger = new Food();
hamburger.calories = 500;
Food spaghetti = new Food();
spaghetti.calories = 700;
Food sausage = new Food();
sausage.calories = 300;

然后用一种方法比较哪种食物的卡路里最低。

public Food findLowestCalories(Food f1, Food f2, Food f3) {

    if (f1.calories < f2.calories && f1.calories < f3.calories){
        return f1;
    } else if (f2.calories < f1.calories && f2.calories < f3.calories){
        return f2;
    } else {
        return f3;
    }

}

然后我有一行打印出findLowestCalories的结果:

System.out.println(findLowestCalories(hamburger, spaghetti, sausage));

我收到错误:对于FoodEater类型,方法findLowestCalories(食物,食物,食物)未定义。

非常感谢任何帮助!

修改

所以FoodEater看起来像这样:

公共级食品饮食者{

public static void main(String[] args) {

    Food hamburger = new Food();
    hamburger.calories = 500;
    Food spaghetti = new Food();
    spaghetti.calories = 700;
    Food sausage = new Food();
    sausage.calories = 300;

    System.out.println(findLowestCalories(hamburger, spaghetti, sausage));

}

}

和我的其他课程一样:

public class FoodMeasure {

public Food findLowestCalories(Food f1, Food f2, Food f3) {

    if (f1.calories < f2.calories && f1.calories < f3.calories){
        return f1;
    } else if (f2.calories < f1.calories && f2.calories < f3.calories){
        return f2;
    } else {
        return f3;
    }

}

}

2 个答案:

答案 0 :(得分:1)

选项1)将方法移至FoodEater。还需要声明为static(原因......)

public static Food findLowestCalories(Food f1, Food f2, Food f3) {

选项2)声明类的实例,以便可以调用该方法。

FoodMeasure measure = new FoodMeasure();
System.out.println(measure.findLowestCalories(hamburger, spaghetti, sausage));

选项3)没有外部方法。将findLowestCalories的所有逻辑移到main方法中。

答案 1 :(得分:0)

您需要构造一个对象FoodMeasure并通过该对象调用findLowestCalories方法。例如:

    FoodMeasure foodMeasure = new FoodMeasure();

    System.out.println(foodMeasure.findLowestCalories(hamburger, spaghetti, sausage));