Java Bootcamp – Workbooks and Challenges
)}

Vending Machine – Part 2

In this workbook, you will apply the Big 3 steps to the Machine class.

Recall, the vending machine is identified by the items that it manages. It also performs the action of dispensing an item.

Task 1 – Adding the field


Add the items field to the Machine class. The items are arranged in rows, so the field needs to be a 2D array.

Task 2 – The Big 3


If a class has fields, you need to apply the Big 3.

  1. Constructor.

    • It receives one parameter: Item[][] items.

    • It uses a nested loop to copy every object from the parameter into the field.

  2. Getter.

    • It receives two parameters: int row and int spot.

    • It returns an object at the requested spot inside a row.

  3. Setter.

    • It receives three parameters: Item item, int row, int spot.

    • It sets an element equal to a copy of the object being passed in.

As you're applying each step, careful not to fall into the reference trap.

Task 3 – Test the constructor.


Inside main(), uncomment the items array. If you removed it, you can find it here.

  • Create an object of the Machine class and pass in the array to the constructor.

  • Then, update the price of the object at row 2 and spot 1 to 2.99 from the outside variable.

  • Get the object at row 2 and spot 1 of the items field.

  • If this is your output, you fell into the trap. Please revisit task 2.

  • If this is your output, you can proceed to task 4.

Task 4 – Test the getters and setters.


Except for the machine object, remove all the code from Task 3.

  • Get the object at row 2 and spot 1 of the items field, and store it in a variable.

  • Set the price of the object to 2.99 from the outside variable.

  • If this is your output, you fell into the trap. Please revisit task 2.

  • Otherwise, call the setter: setItem and pass in the updated object.

  • Get the object at row 2 and spot 1 of items field and print it.

  • Now, seeing a change would be appropriate.

Task 5 – Adding the action.


The next step is to add the dispense action. Use the following doc comment as a guide:

/** * Function name -- dispense * @param row (int) * @param spot (int) * @return (boolean) * * Inside the function: * 1. Checks if the requested item has a quantity bigger than 0. * - if so: decreases its quantity by one and returns true. * - otherwise: returns false. */

Task 6 – Test the action.


Inside main(), remove all code that follows creating the Machine object.

Call the dispense() action twice for the item at row 0, spot 0. Then, print that object. The quantity should decrease from three to one.

>>: Pepsi: 1.99 (1)

Task 7 – Cleaning up.


Inside main(), remove all code that follows creating the Machine object.

Good Luck!

Feedback Summary
4.8
39 students
5

92%
4

3%
3

0%
2

0%
1

5%
Written Reviews
There are no written reviews yet.