AI Hints
Home›Java Tutorial›Reading Input with Scanner, Reading Numbers, Practice: A Receipt
Java · Lesson 27 of 120

Practice: A Receipt

Put module three together.

⏱ 2 min read▶ Video at 35:12🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Let's put module three together. Ask for an item, a price, and a quantity, then print a tidy receipt.

  • Ask three questions
  • Do the maths
  • Print it neatly

A tidy receipt

Your turn. Pause the video, and try this. Ask for an item name, a price, and a quantity. Work out the total. Then print the item line, and the total line, with prices to two decimals. Here is one solution. We read the name first, so there's no leftover enter to worry about. Printf pads the names to ten characters, so the lines line up neatly. Three lattes at three twenty make nine sixty.

✍️ Exercise: A tidy receipt

Ask for item, price and quantity. Print "item qty x price" and "Total" with 2 decimals, names padded to 10.

Show hint

printf("%-10s %8.2f%n", "Total", total)

Show solution
Main.javajava
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Item: ");
        String item = in.nextLine();
        System.out.print("Price: ");
        double price = in.nextDouble();
        System.out.print("Quantity: ");
        int qty = in.nextInt();
        double total = price * qty;
        System.out.println("-------------------");
        System.out.printf("%-10s %d x %.2f%n", item, qty, price);
        System.out.printf("%-10s %8.2f%n", "Total", total);
    }
}
Output
Item: Latte
Price: 3.20
Quantity: 3
-------------------
Latte      3 x 3.20
Total          9.60

What module three taught

Strings are text, with methods like length, trim, and substring. Compare them with equals. Escapes and text blocks handle special text. Format makes tidy output. And Scanner reads text and numbers, from the keyboard.

keyvalue
TextString, + and methods
Compareequals, not ==
Outputprintf, %s %d %.2f
InputScanner

Summary

Your programs can now read input, and print tidy output. That's the end of module three. Next module, making decisions.

Key takeaways
  • Strings
  • Formatting
  • Scanner input
Next up: Comparison Operators — asking questions