Formatting output in columns is what printf is for. Print a shopping receipt whose columns line up.
What to build
A program that prints a receipt with aligned columns and a total.
Requirements
- Read n, then n lines
NAME QUANTITY PRICE(one-word name, whole quantity, price with decimals). - Print each line with the format
%-10s %3d x %7.2f = %8.2f%n(name, quantity, price, line total). - Then print a line of 36
-characters, andTOTALin the format%-26s %9.2f%n.
Input
Line 1: n. Then n lines.
Output
n + 2 lines.
Constraints
1 ≤ n ≤ 20; names have at most 10 letters; quantity ≤ 999; price < 10000.
Example
Input:
2
Pen 3 1.50
Notebook 2 4.25
Output:
Pen 3 x 1.50 = 4.50
Notebook 2 x 4.25 = 8.50
------------------------------------
TOTAL 13.00
Why it works
Format widths pad every value to a fixed width, so the columns line up whatever the numbers are, and a minus sign left-aligns the text column.
Examples
Example 1 · Input
2 Pen 3 1.50 Notebook 2 4.25
Expected output
Pen 3 x 1.50 = 4.50 Notebook 2 x 4.25 = 8.50 ------------------------------------ TOTAL 13.00
Example 2 · Input
1 Tea 1 120
Expected output
Tea 1 x 120.00 = 120.00 ------------------------------------ TOTAL 120.00
Hints
Hint 1
printf("%-10s", name) pads text to 10 characters, left-aligned; %8.2f right-aligns a number in 8.
Hint 2
Keep a running total in a double and print it at the end.
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
double total = 0;
for (int i = 0; i < n; i++) {
String name = in.next();
int qty = in.nextInt();
double price = in.nextDouble();
double line = qty * price;
total += line;
System.out.printf("%-10s %3d x %7.2f = %8.2f%n", name, qty, price, line);
}
System.out.println("-".repeat(36));
System.out.printf("%-26s %9.2f%n", "TOTAL", total);
}
}