Careeroza
Real World Example
Printing a Shopping Bill
Billing software in supermarkets (DMart, Reliance Smart) prints neat receipts with aligned columns. printf widths make that easy.
Example
public class Main {
public static void main(String[] args) {
System.out.println("========= SUPER MART =========");
System.out.printf("%-14s %4s %10s%n", "Item", "Qty", "Amount");
System.out.println("------------------------------");
System.out.printf("%-14s %4d %10.2f%n", "Basmati Rice", 2, 2 * 120.0);
System.out.printf("%-14s %4d %10.2f%n", "Milk 1L", 3, 3 * 54.0);
System.out.printf("%-14s %4d %10.2f%n", "Biscuits", 5, 5 * 10.0);
System.out.println("------------------------------");
double total = 2 * 120.0 + 3 * 54.0 + 5 * 10.0;
System.out.printf("%-19s %10.2f%n", "TOTAL", total);
System.out.println(" Thank you! Visit again.");
}
}Output
========= SUPER MART ========= Item Qty Amount ------------------------------ Basmati Rice 2 240.00 Milk 1L 3 162.00 Biscuits 5 50.00 ------------------------------ TOTAL 452.00 Thank you! Visit again.