4.7 Lab Warmup: Numeric Output Formatting The template code reads in two numbers
ID: 3737043 • Letter: 4
Question
4.7 Lab Warmup: Numeric Output Formatting
The template code reads in two numbers from the user.
Modify the code to:
(1) Use printf to output the numbers rounded to 1 decimal place, so that their decimals line up.
Display leading zeros, with a total of 6 digits displayed before the decimal.
(2) After a blank line, use printf to output the numbers a second time, rounded to 2 decimal places, so that their decimals line up.
Display blanks before the actual digits, with a total of 6 characters appearing before the decimal.
import java.util.Scanner;
public class NumberFormatting {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double num1 = 0.0;
double num2 = 0.0;
System.out.println("Enter two double numbers:");
num1 = keyboard.nextDouble();
num2 = keyboard.nextDouble();
System.out.println();
// FIXME (1): Output to 1 decimal place with leading zeros (6 digits before decimal)
System.out.println();
// FIXME (2): Output to 2 decimal places with leading spaces (6 characters before decimal)
return;
}
}
Explanation / Answer
Paste the following lines of code in the respective places and you will get the result
where %08.1f indicates f-double;'0-number should be preceeded by zero;8-total of 8 characters including"." and 1-decimal no. value.
Both of them follow the same way.
// FIXME (1): Output to 1 decimal place with leading zeros (6 digits before decimal)
System.out.printf("%08.1f ", num1);
System.out.printf("%08.1f ", num2);
// FIXME (2): Output to 2 decimal places with leading spaces (6 characters before decimal)
System.out.printf("%9.2f ", num1);
System.out.printf("%9.2f ", num2);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.