Reputation: 233
I am creating application for canteen management. I must use the overriden method toString() somewhere so i put it in the class Menu for displaying total menu price.But i can`t call the method in my main(). How can i do this ?
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
}
}
Upvotes: 1
Views: 155
Reputation: 11
new Mean(parameters)
, an object of a non-static class .Upvotes: 1
Reputation: 279970
Note that this line
double price = soup.getPrice() + second.getPrice() + desert.getPrice();
will immediately fail. All instance fields are initialized before the constructor body is executed. At that point soup
, second
and desert
are null
. This will throw a NullPointerException
. Instead, add that line at the end of your constructor.
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();
}
For how to call the toString()
method on an instance, see the other answers.
Upvotes: 1
Reputation: 5802
You have to create an instance of Menu and call "toString())" on that because it's not static.
Upvotes: 1
Reputation: 21961
At System.out.println
toString should not manually call. It will call with the instance of object. Try to call like
System.out.println(new Menu()); //toString will automatically call here.
Upvotes: 0
Reputation: 285403
Suggestions:
toString()
methods, including all of the food classes.toString()
method you could then iterate through the foods ordered, calling each one's toString() method in order to build up Menu's own String that it will return.Upvotes: 0