Handson exam CS 21a Section E

  1. Download the following BlueJ Project . Extract and compile the programs under the project. (You will notice that KTester2.java does not compile). Read the following instructions carefully and carry out all the tasks indicated.
  2. There is a working Knapsack class provided in the project. KTester1 is the tester program that creates a knapsack object and calls the methods under this class. Execute KTester1 and study the methods of the Knapsack class. Observe that:
  3. For this handson exam, you will revise Knapsack.java and complete KTester3.java (a bare program has been provided).
  4. Revise Knapsack.java, so that a knapsack now has a weight capacity (this should be an additional instance field). Arrange it so that an item can be added to the knapsack only if the weight of that item is at most 5 lbs. and the total weight of the knapsack will not exceed the knapsack's capacity (Print the message "Cannot add this item" instead). Add a second constructor for Knapsack so that you could indicate its capacity. If the default constructor is used, set the capacity to be 15 lbs. For example:
    Knapsack a = new Knapsack();  // creates a Knapsack whose capacity is 15 lbs
    Knapsack b = new Knapsack(8.8); // creates a Knapsack whose capacity is 8.8 lbs
    Finally, add a getCapacity() method to the Knapsack class that returns the capacity of the knapsack. Here is the documentation page for Knapsack which you may consult.

    KTester2.java tests this new version of Knapsack. Study that program and understand what it is testing. You will know you are done with your revisions if this program compiles and produces the following output:

    Weight capacity of this knapsack: 15.00 lbs.
    The knapsack has 3 items weighing  3.70 lbs.
    Cannot add this item
    The knapsack has 5 items weighing 11.70 lbs.
    Cannot add this item
    Cannot add this item
    Weight capacity of this knapsack:  8.00 lbs.
    The knapsack has 2 items weighing  4.25 lbs.
  5. Complete KTester3.java so that it first asks the user for the following input (use the Scanner class): Then, create a knapsack object with the provided capacity, make three calls to addItem(), one for each of the weights provided, and then print the resulting item count and weight of the knapsack. Here is a sample execution of KTester3 (portions in bold represents user input):
    Type in the weight capacity of the knapsack: 10
    Type in the weight of item 1: 1.5
    Type in the weight of item 2: 2.5
    Type in the weight of item 3: 3.5
    The knapsack has 3 items weighing  7.50 lbs.
    If, in the above execution, you instead input 6 as capacity, one error message should be printed and the knapsack should result in 2 items weighing 4.00 lbs.
  6. Make sure that your name is written in the header comment portion of Knapsack.java and KTester3.java. Zip the revised BlueJ project, and rename the zipfile to Handson1-[Lastname].zip. Submit the zip file via moodle .