Skip to content

Interactive Coffee Vending Machine

Goal

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

Docs for Scanner: https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Scanner.html

Docs for String: https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/String.html

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!");

Step 1: Create a Scanner Instance

In your application's main() method, create an instance of Scanner:

Scanner scanner = new Scanner(System.in);

Scanner's Package

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

Step 2: Display a prompt and get the Coffee Size

  1. Display a prompt (use System.out.println()) 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.

    String input = scanner.nextLine();
    
  3. Take the string that's returned and convert it into the appropriate Size enum.

  4. Use this Size to instantiate a CoffeeOrder and the display the full order.

  5. Try it out before continuing.

Step 3: Creamer & Sweetener

  1. Do the same thing as you did in Step 2 to ask for options for Creamer and Sweetener.

    To make it easier on the user, only require the first letter or two for the choices.

    • For the creamer, allow "m" for milk, "n" for none, and "h" for half-n-half.

    • For the sweetener, allow "n" for none, "su" for sugar, and "sp" for Splenda.

  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.

Step 4: Use While Loop

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

while loops

Documentation for the while loop with break can be found here: https://books.trinket.io/thinkjava/chapter7.html#sec88

Questions:

  • How will you know when to exit the loop based on user input?
  • What code will you write to exit the loop?

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