Search⌘ K
AI Features

User Input with Scanner

Learn how to take user input using Java's Scanner class and format output to create a functional point-of-sale system. This lesson teaches you to prompt for item details, calculate totals and discounts, and produce professional receipts, enabling you to build interactive Java applications.

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 it out in a clear and organized format.

Scanner sc = new Scanner(System.in);
System.out.print("What is your name? ");
String name = sc.nextLine();
System.out.println("Hello, " + name);

We’ll also learn string formatting, which is how we make the printed receipt look neat and professional. Instead of raw numbers and messy text, formatting lets us align and label information clearly. This is so that the receipt is easy for the customer to read. Together, user input and formatting transform our code from something only a coder could use into something accessible to everyone.

The significance of the concept in the project

In our earlier receipt, values like int milkQuantity = 1; and double milkPrice = 4; were typed into the code itself. This meant that if the price of milk changed, the cashier would need to open the file, find the right line, and edit it, which is often slow and error-prone. In a busy store, this is unrealistic and tedious.

With Scanner, we can prompt the cashier like this:

Enter quantity of milk: 1
Enter price of milk: 4

The cashier simply types in the required numbers and presses “Enter.” The program does the rest, calculating totals, formatting the receipt, and printing it neatly. This saves time, reduces mistakes, and means that once the code is written, it doesn’t need to be modified for everyday sales.

Concept at a glance:

  • Scanner sc = new Scanner(System.in); lets us read user input.

  • sc.nextLine() reads text (a string).

  • sc.nextInt() reads a whole number (integer).

  • sc.nextDouble() reads a decimal number.

You can use the stored value in calculations or print it later.

Learn to code for the concept

Let’s start with just the milk example. Instead of writing values directly, we’ll ask the user to enter them:

Scanner sc = new Scanner(System.in);

System.out.print("Enter quantity of milk: ");
int milkQuantity = sc.nextInt();

System.out.print("Enter price of milk: ");
double milkPrice = sc.nextDouble();

System.out.println("Milk (" + milkQuantity + "): " + milkPrice);
Taking the input using the input() function

Here’s what’s happening:

  • System.out.print() shows the message and waits for the user’s response.

  • sc.nextInt() turns the input into a whole number (for quantities).

  • sc.nextDouble() turns the input into a decimal number (for prices).

We can also calculate the total for milk:

C++
System.out.print("Enter quantity of milk: ");
int milkQuantity = sc.nextInt();
System.out.print("Enter price of milk: ");
double milkPrice = sc.nextDouble();
double totalMilk = milkQuantity * milkPrice;
System.out.println("Milk (" + milkQuantity + "): " + milkPrice);
System.out.println("Total for milk: " + totalMilk);

Now, the cashier can type any quantity and price, and the program calculates the correct total instantly; no code editing is needed.

Try running the code again, and give 3 as the quantity and 4 as the price. See how the same code generates the required receipt!

Learn to code with AI

Now that we know how to take input from the user, let’s revisit our full receipt idea:

=== MART RECEIPT ===
Cashier Name: Alex
Items Purchased:
Milk (1): 4
Bread (1): 2
Eggs (12): 0.5 x 12 = 6
Total bill: 4 + 2 + 6 = 12

We’ve coded for milk and its bill, but let’s code for the complete receipt. We’ll need inputs for the cashier’s name and for each item’s quantity and price. The program should calculate subtotals, sum them up for the total bill, and print the results in the neat receipt style showcased above.

Generate code with AI

Today’s entrepreneurial success depends on knowing how to guide AI effectively, and not overstate its ability to generate code for us. As previously stated, we should treat our AI co-partners as well-read, well-educated individuals, being specific in our requests, clear in our expectations, and thorough in the details we provide.

Here’s a prompt you can use with your AI Copilot:

C++
Write a Java program that uses variables, Scanner input, and System.out.println
to generate the given POS receipt. I have written some initial code, but I want the
complete code now:
=== MART RECEIPT ===
Cashier Name: Alex
Items Purchased:
Milk (1): 4
Bread (1): 2
Eggs (12): 0.5 x 12 = 6
Total bill: 4 + 2 + 6 = 12
Initial Code:
Scanner sc = new Scanner(System.in);
System.out.print("Enter quantity of milk: ");
int milkQuantity = sc.nextInt();
System.out.print("Enter price of milk: ");
double milkPrice = sc.nextDouble();
double totalMilk = milkQuantity * milkPrice;
System.out.println("Milk (" + milkQuantity + "): " + milkPrice);
System.out.println("Total for milk: " + totalMilk);

Write your prompt in Copilot:

AI Powered
Saved
5 Attempts Remaining
Reset

Test code with AI

Once the AI has generated the code, copy-paste it into your IDE, run it, and test different scenarios. Try changing quantities and prices to see if the receipt updates correctly. Make sure your formatting matches the sample output exactly.

// Paste your code here
Taking the input using the input() function

If the code does not work and you’re stuck, you should first try to diagnose why it isn’t working. If that fails, try the “Ask AI Mentor” button. If that also doesn’t help you get unstuck, go back to the Copilot and have a chat with it, detailing the problem you faced with the code it generated. If all else fails, click the “Show Solution” button.

Food for thought:

  • What happens if you do not press “Enter” after typing your input?

  • What type of data (text, number, etc.) does Scanner always return before parsing?

  • Is there ever a scenario where you would not want to store the input in a variable?

Practice makes perfect

The more you work with Scanner and formatting, the more natural it becomes to think about code as a conversation between the computer and the person using it. Practice creating short scripts that ask for information, like someone’s name and favorite color, and print it in a neat sentence. Then, move back to the receipt system and try adding more items or better formatting until it looks professional.

Problem

This is the new requirement. You have to write the code that adjusts the discount on the bill:

Code its solution

The given code already asks for user input for items and calculates the total. Your task is to add code that asks for a discount percentage, calculates the discount amount, subtracts it from the total, and updates the receipt output:

// Write your code here
Taking the input using the input() function

Add the discount feature so the program matches the sample output exactly.

If you’re stuck, click the “Show Solution” button.

Congratulations. By now, you’ve learned how to print, take input with Scanner, and perform mathematical operations to make a realistic POS app. Press “Continue” to keep learning. In the next chapter, we’ll make a new app.