Presentation is loading. Please wait.

Presentation is loading. Please wait.

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(,,,..., );

Similar presentations


Presentation on theme: "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(,,,..., );"— Presentation transcript:

1 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(,,,..., ); 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.

2 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.

3 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.

4 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

5 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

6 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.

7 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);


Download ppt "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(,,,..., );"

Similar presentations


Ads by Google