CIS 160 printf

Objective

  • Create formatted output using System.out.printf()

System.out.printf()

  • Usage:
    • System.out.printf(formatString);
    • System.out.printf(formatString, argumentList);
  • the format string can contain text to be printed
  • the format string can also contain format specifiers
  • format specifiers have the following syntax
    %[argument_index$][flags][width][.precision]conversion
    • argument_index indicates the position of the argument in the argument list (this feature will probably not be needed in this course)
    • flags are characters that modify the output and whose meaning depends on the type of conversion being performed
    • width indicates the width of the field (number of characters) being output
    • precision is used to limit how many characters display and whose meaning depends on the type of conversion being performed
    • conversion is a character specifying how the corresponding item in the argument list should be formatted for output
  • conversions
    • s = String
    • c = character
    • d = integer
    • e = floating point with scientific notation
    • f = floating point
    • % = '%'
    • n = platform-specific line separator
  • TestFormatting.java: three ways of formatting numeric output
  • FormatOutput.java: format numeric output (set to two decimal places)
  • TestPrintf.java: formatted output using printf

Examples

  • int n = 6; double x = 1.4733; String name = "Tux";
  • Note: \n and %n both represent a newline character in a format string
  • System.out.printf("Hello\n"); // outputs: Hello\n
  • System.out.printf("Hello%n"); // outputs: Hello\n
  • System.out.printf("The int is %d", n); // outputs: The int is 6
  • System.out.printf("The double is %f", x); // outputs: The double is 1.473300 (6 digits of precision are the default)
  • Note: %7.3f indicates the output should contain 7 characters, with 3 digits after the decimal point. The f indicates a floating-point value is expected.
  • System.out.printf("The double is %7.3f", x); // outputs: The double is 1.473 (width field value causes padding on left)
  • System.out.printf("The double is %5.3f", x); // outputs: The double is 1.473
  • System.out.printf("The double is %4.2f", x); // outputs: The double is 1.47
  • System.out.printf("The double is %4.1f", x); // outputs: The double is 1.5 (rounding happens as needed)
  • System.out.printf("The value is %1d", 17); // outputs: The value is 17 (width field value overridden)
  • System.out.printf("The int is %d", n); // outputs: The int is 6
  • Note: You will almost always want a "\n" at the end of your format string in a printf
  • System.out.printf("n = %d, x = %f\n", n, x); // outputs: n = 6, x = 1.473300\n
  • System.out.printf("Your name is %s\n", name); // outputs: Your name is Tux\n

printf exercise

  • See printf exercise.
  • The same formatting techniques are available through the String.format() method.