gpt4 book ai didi

java - 方法 toString() 问题

转载 作者:行者123 更新时间:2023-11-29 05:34:24 25 4
gpt4 key购买 nike

我正在创建食堂管理应用程序。我必须在某处使用覆盖方法 toString(),所以我将它放在 Menu 类中以显示菜单总价格。但我不能在我的 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

}
}

最佳答案

您必须创建一个 Menu 实例并对其调用“toString())”,因为它不是静态的。

关于java - 方法 toString() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20033503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com