Skip to content

Interactive Coffee Vending Machine

In this lab, we'll take coffee orders from the keyboard in the terminal/console using the Java I/O class and then display the order with its price.

Reference Example

Here's an example of using the Scanner class to get input from the terminal and display it:

  // create a new Scanner to read from the terminal console
  Scanner scanner = new Scanner(System.in);

  // display a prompt
  System.out.println("Name? ");

  // get some text
  String name = scanner.nextLine();
  System.out.println("Hi, " + name + ", nice to meet you.");

  // display an empty line
  System.out.println();

  // display the next prompt
  System.out.println("How many bagels?");

  // get the input as an int
  int qty = scanner.nextInt();
  System.out.println("OK, " + qty + " bagels coming up!");

A. Create a Scanner Instance

In the main() method (inside of the CoffeeVendingMachine class), create an instance of Scanner and pass in the System.in.

Importing the Scanner class

The Scanner class is located in the java.util package.

B. Display a Prompt for Coffee Size

  1. Display a prompt to ask for the coffee size by its first letter: S, M, or L.

  2. Get a line of text from the user, using the nextLine() method that's on the scanner object.

  3. Take the string that's returned and convert it into the appropriate Size enum.

C. Other Options

  1. Do the same to ask for options for Creamer and Sweetener:

  2. Use the choices made to instantiate a CoffeeOrder and the display the full order using the display() method on the CoffeeOrder.

  3. Try it out before continuing.

D. Use While Loop

  1. Surround your code with a while loop so you continue to ask for orders until the user exits.

    while

    Documentation for the while loop (and other loops) can be found here: https://books.trinket.io/thinkjava/chapter7.html

  2. You can exit the while loop at any time by using the break keyword, so write code to ask if the user wants to continue, and if not, exit the loop.


Example Using MealOrder

This is an example that you can look at to help you with your implementation.

public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);

  System.out.println("Burger option: [r]egular, [c]heese: ");
  String burger = scanner.nextLine().toLowerCase();
  if (burger.equals("r")) {
    burger = Burger.BURGER_REGULAR;
  } else {
    burger = Burger.BURGER_CHEESE;
  }

  System.out.println("Drink size: [r]egular, [l]arge: ");
  String size = scanner.nextLine().toLowerCase();
  if (size.equals("r")) {
    size = Drink.DRINK_REGULAR;
  } else {
    size = Drink.DRINK_LARGE;
  }

  MealOrder mealOrder = new MealOrder();

  System.out.println("Meal price is: " + mealOrder.price());
}

Once you've completed the above steps, check in with the instructor to review your code.