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.
JavaDoc Reference Links¶
Docs for Scanner: https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Scanner.html
- You can also look at the FAQ wiki for
Scanneron Reddit: https://www.reddit.com/r/javahelp/wiki/scanner
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¶
-
Display a prompt (use
System.out.println()) to ask for the coffee size by its first letter: S, M, or L. -
Get a line of text from the user, using the
nextLine()method that's on thescannerobject.String input = scanner.nextLine(); -
Take the string that's returned and convert it into the appropriate
Sizeenum. -
Use this Size to instantiate a
CoffeeOrderand the display the full order. -
Try it out before continuing.
Step 3: Creamer & Sweetener¶
-
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.
-
-
Use the choices made to instantiate a
CoffeeOrderand the display the full order using thedisplay()method on theCoffeeOrder. -
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.
Once you've completed the above steps, check in with the instructor to review your code.