Answer to Monday's Formatting Question
This week the programming task was focused on creating formatted Strings using the System.out.printf method.
More specifically you had to use the printf method to create formatted strings that display Math.PI to:
- match the output of
System.out.println(Math.PI);
- only have two decimal places
- have two decimal places and a positive sign (i.e., "+")
- make the calculation of 1-Math.PI have two decimal places and a negative sign (i.e,"-")
- have three leading zeros
And finally, to display the number 1234 as a denary number, a hexadecimal number, an octal number and finally as a denary number with five leading spaces.
Here's my version:
public class Formatting {
public static void main(String[] args) {
System.out.println(Math.PI);
//printf defaults to 6 decimal places
//so to match println command it needs
//15 decimal places
System.out.printf("%.15f%n", Math.PI);
//two decimal places
System.out.printf("%.2f%n", Math.PI);
//two decimal places with positive sign
System.out.printf("%+.2f%n", Math.PI);
//two decimal places with negative sign
System.out.printf("%+.2f%n", 1-Math.PI);
//add three leading zeros
System.out.printf("%011f%n", Math.PI);
//decimal
System.out.printf("%d%n",1234);
//hexadecimal
System.out.printf("%x%n",1234);
//octal
System.out.printf("%o%n",1234);
//add leading five spaces
System.out.printf("% 9d%n",1234);
}
}


No comments yet. Leave a Comment