...

/

User Input with Scanner

User Input with Scanner

Learn to use Java’s Scanner class and basic string formatting by building a receipt generator that lets the cashier enter details directly.

The project

We’ll revisit the POS system one last time. In our previous lesson, the prices, quantities, and names were typed directly into the Java code, which worked fine for us as coders.

But here’s the problem: Is the cashier also a coder? No. They don’t want to open code, find variables, and change values; they just want to type the customer’s details and prices into the system while the customer is standing there.

You’ve been hired to create a smarter version of this point-of-sale system. This is a system where the cashier simply enters the quantities and prices at the command line when the app is running, and the program automatically calculates and prints the receipt. The cashier will not need to look at the code. This is what the receipt looks like:

The programming concept

The programming concept relevant to this lesson is user input. While we know how to display information to the user using System.out.println(), sometimes we need to fetch information from the user instead of displaying it to them.

The user can use their keyboard to type in the required information. Java provides a built-in class called Scanner that lets us ask the user (in this case, the cashier) to type something into the terminal. Whatever they type can then be stored in a variable, just like the ones we learned about earlier. We can then use this data to make calculations or print ...