我正在为食堂管理创建应用程序。我必须在某处使用override方法toString(),所以我将它放在类菜单中以显示总菜单价格。但我不能在main()中调用该方法。我怎样才能做到这一点 ?
class Menu {
private Soup soup;
private SecondMeal second;
private Dessert desert;
public Menu(int soupId, int secId, int desId) {
soup = new Soup(soupId);
second = new SecondMeal(secId);
desert = new Dessert(desId);
}
double price = soup.getPrice() + second.getPrice() + desert.getPrice();
//here is my toString() method
@Override
public String toString() {
String str = "Your menu price is " + price;
return str;
}
}
public class Testing {
public static void main(String [] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
int soupId, secondId, desertId;
do {
System.out.println("Choose soup: ");
Display.soupMenu();
soupId = scan.nextInt();
}
while (soupId < 1 || soupId > 3);
do {
System.out.println("Choose second meal: ");
Display.secondMenu();
secondId = scan.nextInt();
}
while (secondId < 1 || secondId > 3);
do {
System.out.println("Choose dessert: ");
Display.desertMenu();
desertId = scan.nextInt();
}
while (desertId < 1 || desertId > 3);
// here is the problem...
System.out.println(Menu.toString()); // cannot make a static reference to the non-static method
}
}
答案 0 :(得分:1)
你必须创建一个Menu实例并在其上调用“toString())”因为它不是静态的。
答案 1 :(得分:1)
注意这一行
double price = soup.getPrice() + second.getPrice() + desert.getPrice();
会立即失败。在执行构造函数体之前初始化所有实例字段。此时soup
,second
和desert
为null
。这将抛出NullPointerException
。相反,在构造函数的末尾添加该行。
double price;
...
public Menu(int soupId, int secId, int desId) {
soup = new Soup(soupId);
second = new SecondMeal(secId);
desert = new Dessert(desId);
price = soup.getPrice() + second.getPrice() + desert.getPrice();
}
有关如何在实例上调用toString()
方法,请参阅其他答案。
答案 2 :(得分:1)
new Mean(parameters)
,这是一个非静态类的对象。答案 3 :(得分:0)
建议:
toString()
种方法,包括所有食物类别。toString()
方法中,您可以遍历所订购的食物,调用每个人的toString()方法,以便建立它将返回的Menu自己的String。答案 4 :(得分:0)
System.out.println
toString不应手动调用。它将调用object的实例。尝试像
System.out.println(new Menu()); //toString will automatically call here.