| |
Formatting Output | page 5 of 10 |
Formatting output in Java has some technical complexities. Throughout this curriculum guide, we will use a special class, called Format , to format numerical and textual values for a properly aligned output display.
The Format methods are available by including the import directive,
import apcslib.*;
at the top of the source code.
The basic idea of formatted output is to allocate the same amount of space for the output values and align the values within the allocated space. The space occupied by an output value is referred to as the field and the number of character allocated to a field is its field width.
To format an integer you would use the following expressions:
Format.left(int_expression, fieldWidth);
Format.center(int_expression, fieldWidth);
Format.right(int_expression, fieldWidth);
where int_expression is an arithmetic expression whose value is an int and fieldWidth designates the field width. Example:
int i1 = 1234;
int i2 = 567;
int i3 = 891011;
System.out.println(Format.left(i1, 15) + "left");
System.out.println(Format.center(i2, 15) + "center");
System.out.println(Format.right(i3, 15) + "right");
Run output:
1234 left
567 center
891011right
The same type of format statements can be used for a String value.
Format.left(String_expression, fieldWidth);
Format.center(String_expression, fieldWidth);
Format.right(String_expression, fieldWidth);
where String_expression is an expression that evaluates to a String and fieldWidth designates the field width. Example:
String s1 = "left";
String s2 = "center";
String s3 = "right";
System.out.println(Format.left(s1, 15) + "String");
System.out.println(Format.center(s2, 15) + "String");
System.out.println(Format.right(s3, 15) + "String");
Run output:
left String
center String
rightString
To format a real number (float or double ) we need additional arguments to specify the decimal places:
Format.left(real_expression, fieldWidth, decimalPlaces);
Format.center(real_expression, fieldWidth, decimalPlaces);
Format.right(real_expression, fieldWidth, decimalPlaces);
where real_expression is an arithmetic expression whose value is either a float or a double and decimalPlaces designates the number of digits shown to the right of the decimal point. The value for fieldWidth must be at least as large as the value of decimalPlaces plus two. Example:
double d1 = -123.4e-5;
double d2 = 678.9;
double d3 = 12345.6789;
System.out.println(Format.left(d1, 15, 6) + "left");
System.out.println(Format.center(d2, 15, 3) + "center");
System.out.println(Format.right(d3, 15, 2) + "right");
Run output:
-0.001234 left
678.900 center
12345.68right
|