Practice Quiz 5 - Solutions


  1. Write the statement that belongs in the method below that should print the restaurant, name, and price of an item. This method is in a different class; it is passed the item as a parameter.

        public void printItem(MenuItem item)
        {
            // System.out.println CODE MISSING -- type it below in the answer box!
        } 

    Solution:

            System.out.println(item.getRestaurant() + ": " +
                    item.getItemName() + "  (" + item.getPrice() + ")");
  2. Write a loop that prints each item on a separate line, using the printItem method you completed above. Assume this code is in the same class as the printItem method, so you can call it using "this.printItem(someItem);"

    Solution:

        for ( MenuItem item : menuList )
        {
            this.printItem(item);
        } 
  3. If you wanted to print all items in the list that include “Naan” (any type of Naan), which condition would you add before the System.out.println statement in the code segment in Question #2? (Assume you used a variable called `item` to refer to each item in the list.)

    Solution:

        // First option
        for ( MenuItem item : menuList )
        {
            if ( item.getItemName().contains("Naan"))
                this.printItem(item);
        } 
  4. Which of the following code fragments correctly prints how many items in the list come from the restaurant named “Hopcat"?

    Solution:

    A.  int count = 0;
        for ( MenuItem item: menuList)
        {
            if ( item.getRestaurant().equals("Hopcat") )
                count++;
        }
        System.out.println(count);