Formatted Output
Problem
Read a name, an age (whole number) and a price (decimal number) on one line. Print two lines. Line 1: Name: <name>, Age: <age>, Price: <price with 2 decimals>. Line 2: the name in a field of 8 characters, left aligned, then the price in a field of 10 characters, right aligned, with 2 decimals, each field in square brackets. Example: [Asha ][ 49.50].
Constraints
- The name has no spaces
Examples
Input
Asha 21 49.5
Output
Name: Asha, Age: 21, Price: 49.50 [Asha ][ 49.50]
Solutions
Format codes control how a value is written: the number of decimals, the width of a field, and the alignment. Java uses printf with % codes, Python uses f-strings, JavaScript uses toFixed, padEnd and padStart. Note: for values such as 7.005 (which cannot be stored exactly) Java rounds differently from JavaScript and Python, so avoid tie values when you compare outputs.
/*
* Problem : Print values with formatting.
* Input : A name, an age and a price on one line.
* Output : Two lines: a summary line and an aligned line.
* Approach: Use the format feature of the language.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Step 1: Locale.US makes the scanner and the formatter use a dot as the decimal separator.
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
String name = scanner.next();
int age = scanner.nextInt();
double price = scanner.nextDouble();
// Step 2: %s is for text, %d is for a whole number, %.2f is for a decimal number with 2 digits. %n starts a new line.
System.out.printf(Locale.US, "Name: %s, Age: %d, Price: %.2f%n", name, age, price);
// Step 3: %-8s means: text, 8 characters wide, aligned to the left. %10.2f means: 10 characters wide, aligned to the right.
System.out.printf(Locale.US, "[%-8s][%10.2f]%n", name, price);
}
}
Hints (2)
- Which format code writes a decimal number with 2 digits?
- What is the difference between left and right alignment?