Java Reference
In-Depth Information
System.out.printf
System.out.printf is used for formatted screen output. System.out.printf can have
any number of arguments. The first argument is always a format string for the remaining
arguments. All the arguments except the first are values to be output to the screen, and
these values are output in the formats specified by the format string. The format string can
contain text as well as format specifiers, and this text is output along with the values.
Self-Test Exercises
5. What output is produced by the following code?
String aString = "Jelly beans";
System.out.println("START1234567890");
System.out.printf("START%sEND %n", aString);
System.out.printf("START%4sEND %n", aString);
System.out.printf("START%13sEND %n", aString);
System.out.println();
6. What output is produced by the following code? For each output line, describe
whether the line begins or ends with a blank or blanks.
String aString = "Jelly beans";
double d = 123.1234567890;
System.out.println("START1234567890");
System.out.printf("START%sEND %n %9.4f %n", aString, d);
7. Write a Java statement to output the value in variable d of type double to the
screen. The output should be in e -notation with three digits after the decimal
point. The output should be in a field of width 15.
Money Formats Using NumberFormat
Using the class NumberFormat , you can tell Java to use the appropriate format when
outputting amounts of money. The technique is illustrated in Display 2.3. Let's look
at the code in the main method that does the formatting. First consider the following:
NumberFormat
NumberFormat moneyFormatter =
NumberFormat.getCurrencyInstance();
The method invocation NumberFormat.getCurrencyInstance() produces an object of the
class NumberFormat and names the object moneyFormatter . You can use any valid identifier
Search WWH ::




Custom Search