The printf Method

7
The printf Method The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(<format string>, <arg 1 >, <arg 2 >, ..., <arg n >); The format string is a string that specifies how to print out the output, and the args specify the values that are to be printed out.

description

The printf Method. The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(, , , ..., ); - PowerPoint PPT Presentation

Transcript of The printf Method

Page 1: The printf Method

The printf Method

The printf method is another way to format output. It

is based on the printf function of the C language.

System.out.printf(<format string>, <arg1>,

<arg2>, ..., <argn>);

The format string is a string that specifies how to

print out the output, and the args specify the values

that are to be printed out.

Page 2: The printf Method

Example

String name = "Foobear";int n = 10;double f = -132.5;System.out.printf("%s %5d %6.2f", name, n, f);

will print out:

Foobear 10 -132.50

with no end of line at the end.

Page 3: The printf Method

Format Specifiers

The format string contains format specifiers. There is

a format specifier corresponding to each argument.

The first format specifier is used for the first

argument, the second for the second argument, and

so on. The format specifier specifies the how the

argument is to be interpreted (decimal, fixed-point,

exponential notation, string, character), and,

optionally, the field width, the precision, and the

justification.

Page 4: The printf Method

Specifier Form

The general form of a format specifier is:

%-w.pc

where – means to left justify, w is the field width, p

is the precision, and c is the conversion character.

Everything is optional except for the '%' and c.

Thus, a format specifier could be just

%c

Page 5: The printf Method

Conversion Characters

The most commonly used conversion characters are: d – decimal (ordinary) integer f – fixed point floating point number e – exponential (scientific notation) floating point g – general floating point (Java decides between

the previous two) s – string c - character

Page 6: The printf Method

Optional Specifications

The optional parts of the format specifier are: - left justify. Without this, the value is right

justified. w – (an integer) field width. If the value printed

out takes fewer than w columns, it is padded with

spaces. p – (an integer) precision. The number of digits to

the right of the decimal point.

Page 7: The printf Method

Added Text

The format string may also contain text, which is

printed out as is. This is used for labels, for $ (for

money), spacing, and new lines. The code %n will

output a new line character.

System.out.printf("You are owed $%6.2f. %n", money);