Printf 在Java中的用法介绍

最后更新于:2022-03-30

此文章最后编辑于 8 个月前,部分信息可能已经过时,请自行斟酌确认。

How printf() works?

String account = "Prime";
double total = 210.35;
int years = 5;

System.out.printf("The %s account saved you $%f over %d years\n",
    account, total, years);

printf() and format() methods

A programmer can adjust the way that a program's output appears, a task known as output formatting. The standard output stream System.out provides the methods printf() and format() for output formatting. Both methods are equivalent, so this discussion only refers to printf().

The first argument of the printf() method, the format string, specifies the format of the text to print along with any number of placeholders for printing numeric values. The placeholders are known as format specifiers. A format specifier specifies the type of value to print in its place. A format specifier begins with the % character followed by another character that indicates the value type to be printed. Ex: %d indicates an integer type, and %s indicates a string type.

Table 1: Format specifiers for the printf() and format() methods.

Format specifierData type(s)Notes
%ccharPrints a single Unicode character
%dint, long, shortPrints a decimal integer value.
%oint, long, shortPrints an octal integer value.
%hint, char, long, shortPrints a hexadecimal integer value.
%ffloat, doublePrints a floating-point value.
%efloat, doublePrints a floating-point value in scientific notation.
%sStringPrints the characters in a String variable or literal.
%% Prints the "%" character.
%n Prints the platform-specific new-line character.

Floating-point values

Formatting floating-point output is commonly done using sub-specifiers. A sub-specifier provides formatting options for a format specifier and are included between the % and format specifier character. Ex: The .1 sub-specifier in printf("%.1f", myFloat); causes the floating-point variable myFloat to be output with only 1 digit after the decimal point; if myFloat is 12.34, the output would be 12.3. Format specifiers and sub-specifiers use the following form:

%(flags)(width)(.precision)specifier

The table below summarizes the floating-point sub-specifiers available. Assume myFloat has a value of 12.34. Recall that %f is used for floating-point values and %e is used to display floating-point values in scientific notation.

Table 2: Floating-point formatting

Method calls to printf() apply to PrintStream objects like System.out.

Sub-specifierDescriptionExample
widthSpecifies the minimum number of characters to print. If the formatted value has more characters than the width, the value will not be truncated. If the formatted value has fewer characters than the width, the output will be padded with spaces (or 0's if the '0' flag is specified).printf("Value: %7.2f", myFloat); Value: 12.34
.precisionSpecifies the number of digits to print following the decimal point. If the precision is not specified, a default precision of 6 is used.printf("%.4f", myFloat); 12.3400 printf("%3.4e", myFloat); 1.2340e+01
flags-: Left aligns the output given the specified width, padding the output with spaces. +: Prints a preceding + sign for positive values. Negative numbers are always printed with the - sign. 0: Pads the output with 0's when the formatted value has fewer characters than the width. space: Prints a preceding space for positive value.printf("%+f", myFloat); +12.340000 printf("%08.2f", myFloat); 00012.34

Integer values

Formatting of integer values is also done using sub-specifiers. The integer sub-specifiers are similar to the floating-point sub-specifiers except no .precision exists. For the table below, assume myInt is 301.

Table 3 Integer formatting.

Method calls to printf() apply to PrintStream objects like System.out.

Sub-specifierDescriptionExample
widthSpecifies the minimum number of characters to print. If the formatted value has more characters than the width, the value will not be truncated. If the formatted value has fewer characters than the width, the output will be padded with spaces (or 0's if the '0' flag is specified).printf("Value: %7d", myInt); Value: 301
flags-: Left aligns the output given the specified width, padding the output with spaces. +: Print a preceding + sign for positive values. Negative numbers are always printed with the - sign. 0: Pads the output with 0's when the formatted value has fewer characters than the width. space: Prints a preceding space for positive value.printf("%+d", myInt); +301 printf("%08d", myInt); 00000301 printf("%+08d", myInt); +0000301

Strings

Strings may be formatted using sub-specifiers. For the table below, assume the myString variable is "Formatting".

Table 4: String formatting.

Method calls to printf() apply to PrintStream objects like System.out.

Sub-specifierDescriptionExample
widthSpecifies the minimum number of characters to print. If the string has more characters than the width, the value will not be truncated. If the formatted value has fewer characters than the width, the output will be padded with spaces.printf("%20s String", myString); Formatting String
.precisionSpecifies the maximum number of characters to print. If the string has more characters than the precision, the string will be truncated.printf("%.6s", myString); Format
flags-: Left aligns the output given the specified width, padding the output with spaces.printf("%-20s String", myString); Formatting String

Flushing output

Printing characters from the buffer to the output device (e.g., screen) requires a time-consuming reservation of processor resources. Once the resources are reserved, moving characters is fast, whether there is 1 character or 50 characters to print.

To preserve resources, the system may wait until the buffer is full, or at least has a certain number of characters before moving them to the output device. Or, with fewer characters in the buffer, the system may wait until the resources are not busy. Sometimes a programmer does not want the system to wait. Ex: In a very processor-intensive program, waiting could cause delayed and/or jittery output.

The PrintStream method flush() flushes the stream's buffer contents. Ex: The statement System.out.flush(); writes the contents of the buffer for System.out to the computer screen. Most Java implementations make System.out flush when a newline character is output or println() method is called.

文章目录

标签: Java

评论已关闭。 了解详情