Practice Quiz on Writing Code in Methods

  1. Assume you have a MenuItem class that has the following 3 methods (and possibly other methods as well):
        public String getItemName()   { /* body not shown */ }
        public String getRestaurant() { /* body not shown */ }
        public double getPrice()      { /* body not shown */ } 
    Write the statement that belongs in the method below that should print the restaurant, name, and price of an item. The method printItem(MenuItem item) is in a separate Menu class, not the MenuItem class; it receives the MenuItem object (item) as a parameter.
    public class Menu
    {
        ArrayList menuList;
    
        public void printItem(MenuItem item)
        {
        
        }
        ...
    Format of sample output:
        Hunan Gardens:  Spring roll   ($6.99)
    (Don't worry about spacing or how many digits get printed for the price — $6.9991121 would also be fine.)
  2. Assume your Menu class has an instance variable that is an ArrayList of MenuItem objects called menuList. Write a for loop in a printAll method in the Menu class that prints information about each MenuItem object on a separate line, using the printItem method you completed above.
        // Still in Menu class
        public void printAll()
        {
        
        } 
    Sample partial output:
        Hunan Gardens:  Spring roll   ($6.99)
        Saffron:  Garlic Naan   ($3.99)
  3. If you wanted the printItem method to only print an item if its name includes "Naan" (any type of Naan), which condition would you add before the System.out.println statement in Question #1?
    a)   if ( getItemName(item) == "Naan" )
    b)   if ( item.getItemName() == "Naan" )
    c)   if ( item.getItemName().equals("Naan") )
    d)   if ( equals(getItemName(item), "Naan" )
    e)   if ( item.getItemName().contains("Naan") )
    f)   if ( contains(getItemName(item), "Naan" )