Vending machine

Report a typo

In this code challenge, you are given an implementation of the VendingMachine class that simulates a vending machine with a display and two buttons, left and right. When the machine starts, it displays the product menu where the user may select a product they wish to buy. The user may cycle through the products by pressing the right button and select a product by pressing the left button. After the product is selected, the machine displays another menu where the user may select how many items of the selected product they want.

In the second menu, the user may cycle through the possible numbers, from 0 to 4, by pressing the right button, and select the desired number of items by pressing the left button. The initial quantity is 1. Each time the user presses the right button, the selected quantity is increased by 1 and displayed.

The provided template uses the State pattern, and your task is to write the two methods of MenuQuantity class to satisfy the following logic:

If the selected quantity is 0, the program must print Cancelled and return to the first menu. If any other quantity is selected, the program must print Dispensing %quantity% packages of %product% where %quantity% is the selected quantity and %product% is the selected product and return to the first menu.

See the examples to get a better idea of how the simulation works.

Sample Input 1:

left
right
left

Sample Output 1:

Vending machine is on
Select item:
Juice
How many Juice do you want?
1
2
Dispensing 2 packages of Juice
Select item:
Juice

Sample Input 2:

right
right
left
right
right
right
right
left

Sample Output 2:

Vending machine is on
Select item:
Juice
Soda
Cold Tea
How many Cold Tea do you want?
1
2
3
4
0
Cancelled
Select item:
Juice
Write a program in Java 17
import java.util.List;
import java.util.Scanner;

interface State {
void onLeftPressed();

void onRightPressed();
}

class VendingMachine {
private final List<String> products = List.of("Juice", "Soda", "Cold Tea");
private State state;

VendingMachine() {
System.out.println("Vending machine is on");
state = new MenuProducts(this);
}

public void pressLeft() {
state.onLeftPressed();
}

public void pressRight() {
state.onRightPressed();
}

public void setState(State state) {
this.state = state;
}

public List<String> getProducts() {
return products;
}
}

class MenuProducts implements State {
___

Create a free account to access the full topic