JMU
Answers to Examination 1, Spring 2011


  1. (20 points) Choose the best answer to each of the following:
    (1) c In Java, StringTokenizer is a:
    1. Primitive type
    2. Value type
    3. Reference type
    4. All of the above
    (2) d Two methods in the same class with the same name but different parameters are said to be:
    1. Overridden
    2. Encapsulated
    3. Typecast
    4. None of the above
    (3) b In Java:
    1. Static attributes never change
    2. Static attributes belong to the class
    3. Both of the above
    4. Neither of the above
    (4) b In Java, if the int named age is declared protected in the class Person, age is accessible/visible in:
    1. All objects in all classes
    2. All objects in the class Person and all descendents of the class Person
    3. Only objects in the class Person
    4. None of the above
    (5) c Given the following declaration:
          enum Tree { PINE, MAPLE, OAK }      
          
    what would be output by the following?
          Tree hard, soft;
    
          hard = Tree.OAK;
          soft = Tree.PINE;
    
    
          System.out.println((hard.compareTo(soft) > 0));            
          
    1. Tree
    2. false
    3. true
    4. "Harder"
    (6) d In Java, all methods must have:
    1. A return statement
    2. Mutiple parameters
    3. An enumerated type
    4. None of the above
    (7) c In Java, which of the following uses a post test?
    1. for loop
    2. while loop
    3. do-while loop
    4. a and b
    (8) b In Java, which of the following statements declares Salaried as a subclass of PayType?
    1. public class Salaried subclass PayType
    2. public class Salaried extends PayType
    3. public class Salaried specializes Paytype
    4. public class PayType extends Salaried
    (9) c In the Java statement, System.out.println("Hi");, out is:
    1. A public method in the PrintWriter class
    2. A protected class
    3. A static attribute in the System class
    4. An operating system command
    (10) ? Working on Programming Assignment 2 was:
    1. The most fun I've had in three years
    2. Better than ice cream
    3. The reason I changed my major to Art History
    4. Why I didn't have a date on Valentine's Day
    5. All of the above

  2. (30 points) Given the attached Item, Clothing, Food, and Income classes (in the same package/directory) and the following declarations and method in TaxDriver:
    public class TaxDriver
    {
        public static void main(String[] args)
        {
           Clothing   shirt;       
           double     total;       
           Food       lettuce;
           Income     salary;       
           Item       mop, pan, wax;       
           Item[]     july;
           String     outString;       
    
           july    = new Item[10];       
           salary  = new Income("Bonus", 25000.00);       
           mop     = new Item("Swiffer", 8.75);       
    
    
           // The code in the questions below will be inserted here
    
        }
    }
      

    indicate which of the following statements will "compile" (C) and which will "not compile" (N), where "compile" means that it will compile without generating an error. Note: Each statement should be considered independently.

    In the constructor of the Food class (after the first line):
    (1) N super.description = "CS239 Rocks!";
    (2) C super(price); (replacing the first line)
    (3) C taxRate = 0.20;
    In the main() method of TaxDriver (after the declarations):
    (4) C mop.taxRate = 0.50;
    (5) C mop.setPrice(9.00);
    (6) N shirt = new Clothing(10.00);
    (7) C pan = new Item(15.00);
    (8) C wax = new Item("Floor Wax", 3.00);
    (9) N lettuce = new Item("Mixed Greens", 2.50);
    (10) N outString = salad.toString();
    (11) N tax = salary.tax();
    (12) C july[0] = pan; (Assuming pan has been instantiated)
    (13) C july[1] = new Item("Toothpaste", 2.59);
    (14) N july[2] = "Lettuce";
    (15) N july[3] = salary; (Assuming salary has been instantiated)

    For each of the statements above that will "not compile", state why it will not compile. (Provide the statement number in the parentheses.) You do not need to state anything for the statements that will "compile".

    (1) description has private access in Item

    (6) The Clothing class does not have a corresponding constructor (and constructors are not inherited).

    (9) Incompatible types (you can't assign an Item to a Food because an Item isn't a Food).

    (10) Cannot find symbol (outString has not been declared).

    (11) Cannot find symbol (tax has not been ).

    (14) Incompatible types (you can't assign an String to an Item).

    (15) Incompatible types (you can't assign an Income to an Item even though the Income class has all of the same methods as the Item class).


  3. (20 points) Given the attached Item, Clothing, Food, and Income classes (in the same package/directory), show what will be printed by the following driver, assuming everything is compiled and executed properly.

    Notes: (1) Your formatting does not have to be exact, but be careful. (2) The classes in this question do not contain any intentional syntax errors.

    public class DogDriver
    {
        public static void main(String[] args)
        {
           Clothing  shirt;       
           Food      lunch;       
           Item      bone;
           Item[]    dog;
           
           
           dog  = new Item[3];
    
           bone = new Item("Jumbone", 2.59);
           dog[0] = bone;
    
           dog[1] = new Item("Leash", 22.50);       
    
           bone.setPrice(1.00);
           dog[2] = bone;
    
           for (int i=0; i<dog.length; i++)
           {
              System.out.println(dog[i].toString());
           }
    
           System.out.println();       
    
           lunch = new Food("Pizza", 5.00);
           System.out.println("Lunch: " + lunch.tax());
    
           shirt = new Clothing("Striped", 10.00);
           System.out.println("Shirt: " + shirt.tax());
        }
    }
    
       Jumbone   1 $ 1.00
         Leash   2 $22.50
       Jumbone   1 $ 1.00
    
    Lunch: 0.25          
    Shirt: 3.0           
    

  4. (15 points) Given the attached Item, Clothing and Food classes, complete the add() and totalTax() methods in the following Receipt class. Your solution must be consistent with the comments describing the methods. You must not change any other methods or attributes. You must not duplicate any existing code unless it is necessary to do so.
    public class Receipt
    {
        private Item[]             items;    
        private int                size;    
    
        
        public Receipt(int maxSize)
        {
           items    = new Item[maxSize];
           
           for (int i=0; i<maxSize; i++)
           {
              items[i]    = null;
           }
           size = 0;
        }
    
        /**
         * Adds an Item object to this Receipt (if there are
         * not already maxSize elements in it).  Specifically,
         * this method assigns the Item object to the first null
         * element in the array.
         *
         * @param item   The Item object to add
         */
        public void add(Item item)
        {
    
           if (size < items.length)
           {
              items[next] = item;     
              ++size;                 
           }
    
        }
        
    
    
    
        /**
         * Calculates the total tax of all Item objects in this Receipt.
         * Specifically, loops over all of the Item objects
         * in this Receipt, gets the tax for each, and adds
         * them up.  NOTE: This method works properly even if
         * the array is only partially full.
         *
         * @return          The total tax
         */
        public double totalTax()
        {
    
           double     total;                
           
           total = 0.0;                     
           for (int i=0; i<size; i++)    
           {
              total += items[i].tax();       
           }
           
           return total;                     
    
        }
    }
    

  5. (15 points) Complete the getVolume() method, the isOversized() method, and the two-parameter explicit value constructor in the following Container class. Your solution must be consistent with the comments describing the methods. You must not change any other methods or attributes. You must not duplicate any existing code unless it is necessary to do so. (Advice: From a time management perspective, you may want to work on the explicit value constructor last.)
    import java.util.*;
    
    /**
     * An encapsulation of a shipping container
     */
    public class Container
    {
        private double depth, height, weight, width;
    
        private static final double LIMIT      =   10.00;    
        private static final double MAX_VOLUME = 1000.00;    
        private static final double MAX_WEIGHT =  200.00;    
    
        /**
         * Explicit Value Constructor
         *
         * @param width   The width
         * @param height  The height
         * @param depth   The depth
         * @param weight  The weight
         */
        public Container(double width, double height, double depth,
                         double weight)
        {
           setAttributes(width, height, depth, weight);
        }
        
        /**
         * Explicit Value Constructor
         *
         * This explicit value constructor is passed a String
         * representation of the size delimited by 'x' characters
         * and a weight.  For example, this constructor might be
         * used as follows:
         *
         *     container = new Container("10.00x5.00x20.00", 100.00)
         *
         * where 10.0 is the width, 5.00 is the height, and 20.00 is the depth.
         * A standard Container (with size 1 by 1 by 1 and weight 100)
         * is constructed if the size is invalid in any way.
         *
         * @param size    A String representation of the size
         * @param weight  The weight
         */
        public Container(String size, double weight)
        {
    
           double                dvalue, hvalue, wvalue;
           String                dtoken, htoken, wtoken;       
           StringTokenizer       st;
           
           st = new StringTokenizer(size, "x");
           try
           {
              wtoken = st.nextToken();                 
              htoken = st.nextToken();
              dtoken = st.nextToken();
    
              wvalue   = Double.parseDouble(wtoken);   
              hvalue   = Double.parseDouble(htoken);
              dvalue   = Double.parseDouble(dtoken);
    
              setAttributes(wvalue, hvalue, dvalue, weight); 
           }
           catch (NumberFormatException nfe)                 
           {
              setAttributes(1.00, 1.00, 1.00, 100.00);     
           }
           catch (NoSuchElementException nsee)
           {
              setAttributes(1.00, 1.00, 1.00, 100.00);          
           }
    
        }
        
    
        /**
         * Returns the volume of this Container (which is simply
         * the width times the height times the depth)
         */
        public double getVolume()
        {
    
           return width*height*depth;            
    
        }
        
    
    
        /**
         * Returns true if any or all of the following are true:
         *
         *    The volume is greater than MAX_VOLUME
         *    The weight is greater than MAX_WEIGHT
         *    The ratio of the volume to the weight is greater than LIMIT
         */
        public boolean isOversized()
        {
    
           boolean         result;
           double          ratio, volume;       
           
           volume = getVolume();       
           ratio  = volume / weight;   
           
           result = (volume > MAX_VOLUME) || (weight > MAX_WEIGHT)  ||
                    (ratio  > LIMIT);       
    
           //This could also be written as:
           //result = false;
    
           //if ((volume > MAX_VOLUME) || (weight > MAX_WEIGHT)  ||
           //    (ratio  > LIMIT)) result = true;       
    
           return result;             
    
        }
    
    
        /**
         * Set all of the attributes of this Container
         *
         * @param width   The width
         * @param height  The height
         * @param depth   The depth
         * @param weight  The weight
         */
        private void setAttributes(double width, double height, double depth,
                                   double weight)
        {
           this.width  = Math.abs(width);
           this.height = Math.abs(height);
           this.depth  = Math.abs(depth);
           this.weight = Math.abs(weight);       
        }
    }
    

ATTACHMENTS

public class Item
{
    protected static double taxRate  = 0.10;    
    private   static int    lastCode = 0;
    
    private   double   price;    
    private   int      code;
    private   String   description;    
    

    public Item(double price)
    {
       this("Unknown", price);       
    }
    
    public Item(String description, double price)
    {
       this.description = description;
       this.price       = price;       

       lastCode++;       
       code = lastCode;       
    }

    public double getPrice()
    {
       return price;       
    }

    public void setPrice(double price)
    {
       this.price = price;       
    }
    
    public double tax()
    {
       return taxRate * price;       
    }

    public String toString()
    {
       return String.format("%10s %3d $%5.2f", description, code, price);
    }
    
}

public class Food extends Item
{
    public Food(String description, double price)
    {
       super(description, price);       
    }
    

    public double tax()
    {
       return taxRate/2.0 * getPrice();
    }
}

public class Clothing extends Item
{
    public Clothing(String description, double price)
    {
       super(description, price);       
    }
    
    public double tax()
    {
       return 2.00 + super.tax();       
    }
    
}
public class Income
{
    private static double taxRate = 0.10;    

    private double    amount;
    private String    description;    

    public Income(String description, double amount)
    {
       this.description = description;
       this.amount      = amount;       
    }
    

    public double tax()
    {
       return taxRate * amount;       
    }
}

Copyright 2011