Skip to main content
ICT
Lesson A7 - Simple I/O
 
Main   Previous Next
 

C. Formatting Output page 5 of 7

  1. To format, we will learn a new printing method, printf(). It works similarly to the print() and println() methods that you have already been using to output text.

  1. The printf() method takes two arguments. The first one is the formatting String, a special sequence of characters that tells printf() how to display the second argument. The syntax for the formatting String is:

    %[flags][width][.precision]conversion

    The ‘%’ sign tells the printf method that formatting is coming. All of your formatted String constants will start with %. It does not have to be the very first thing in your String constant, just the first part of any formatted text.

  2. The last part of the formatting String, conversion, is one of the most important parts. It is what determines how the printf() method reacts to a message you send it. The most important conversion tags for you to know are ‘s’, ‘d’, and ‘f’. ‘d’ is used for integers (base-10 notation), ‘f’ is for numbers with decimal places (doubles), and ‘s’ is for String literals. The conversion tag always comes at the end of the formatting String.

    Conversion Tag
    Usage Type
    Example
    s
    String literals printf("%s", "Sam")
    d
    ints printf("%d", 5182)
    f
    doubles printf("%f", 2.123456)

     

  3. Precision is very easy and straightforward. When using a formatting String with the ‘s’ conversion tag, this will tell printf() the maximum number of characters to print out. When used with the ‘f’ conversion tag, you can specify how many decimal places to print out, rounded to the closest number. If you don’t specify how many decimal places to display with ‘f’ then it will default to six places.

    System.out.printf("%.2s", "Hello") -> He
    System.out.printf("%.10s", "Hello") -> Hello
    System.out.printf("%.5f", Math.PI) -> 3.14159
    System.out.printf("%.4f", Math.PI) -> 3.1416
    System.out.printf("%f", Math.PI) -> 3.141593

  4. Width tells printf() the minimum number of characters to print out. This allows for creating right-aligned lists or menus. printf() does not distinguish between normal characters and special characters (escape sequences), so "Prices:" and "Prices:\n" are two different sizes. If you want to print your data out left-aligned, you can simply add a ‘-‘ character to the left of the width value.

    Note: In the example below, the first line has a width of 11 instead of 10 to adjust for the \n error. Because numeric entries cannot use these special characters, it is better to use println() to separate lines when utilizing printf(). The example below shows one instance of using the \n character as well as doing two columns of formatted output.

    System.out.printf("%-10s", "Name:");
    System.out.printf("%11s", "Price:\n");
    System.out.printf("%-10s", "Soda");
    System.out.printf("%10.2f", 10.25);
    System.out.println();
    System.out.printf("%-10s", "Candy");
    System.out.printf("%10.2f", 1.50);

    Output:

    Name:      Price:
    Soda        10.25
    Candy        1.50

  5. Flags are special characters that give special properties to the values passed in. Adding a ‘+’ sign in the formatting String will give numbers a positive or negative sign when printed. Putting in a ‘(’ will cause negative numbers to be enclosed with parentheses. The most useful of the flags is ‘,’ because it will add commas into large numbers (in the correct spot for the region, i.e. Japan puts numbers into groups of four unlike the US, which puts numbers in groups of three). To get a dollar sign directly before your printed value, place the ‘$’ character directly before the ‘%’ sign.

    System.out.printf("%,d", 12345678) -> 12,345,678
    System.out.printf("$%,d", 12345678) -> $12,345,678
    System.out.printf("%,(d", 12345678) -> 12,345,678
    System.out.printf("%,(d", -12345678) -> (12,345,678)

  6. You may put multiple arguments in one call to printf() for organizational purposes. Simply put multiple formatting Strings in the first passed argument to printf() and then add your additional arguments, separated by commas.

    double mySum = 123.456
    System.out.printf("%10s %10.2f", "Total:", mySum);

  7. This curriculum uses just a few of the many things that printf() is capable of. Once you get more familiar with using the formatting options shown in this guide, you can look at the API for the Formatter class for more information on formatting Strings. The printf() method is an easy way to manage the Formatter class in a way that is very similar to the common print() and println() functions.

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.