user2976091 user2976091 - 2 years ago 80
Java Question

Method toString() issue

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

}
}

Answer Source

Suggestions:

  • You need to create a Menu instance in the main method in order to call methods on it. I'd start there.
  • Your other classes should have toString() methods, including all of the food classes.
  • Within Menu's 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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download