1-5 Fancy Output

So far we’ve seen the print() and println() methods in action, but there is much more we can do to control the way our program output is displayed!

Escape Sequences

What if we’d like to add a new line, tab, or double quotation (“) mark to our output string? For obvious reasons, you can’t just type these as part of the output (try it!). To enable this, Java supports what are called escape sequences. An escape sequence is made up of a character preceded by a backslash (\) that has special meaning to the Java compiler.

Here’s an example to demonstrate these in action. Try and predict the output before running it:

Vik-20 says:
Press “Enter” to save c:\java\Hello.java

Formatted Printing

For even more formatted printing options, Java provides the printf() method. Consider the following example:

Here’s the output:

Welcome to Grade 12!
PI = 3.142
True OR False is true
J. Bond

The first argument to the printf() method call is a string that may consist of fixed text and format specifiers. A format specifier is a placeholder for a value that specifies the type of data to output. Format specifiers start with a percent sign (%) and are followed by a character that represents the data type to be displayed at that point in the output string. Common format specifiers include:

With %f you can specify the total number of digits (including the decimal point) that you’d like, followed by a dot (.), followed by the number of digits that you’d like after the decimal. The float value is rounded (not truncated) to the precision you specify. Note that printf() is like print() in that it does not automatically go to a new line. If you want that, you’ll need to include the \n escape character as shown in the example code.

You try!

    1. Add an entry for “1-5 Fancy Output” in your Learning Journal and answer the following questions:
      1. Explain the result of each of the format specifiers in the code below. Pay special attention to the and . symbols and their effects on the output.
      2. Update your glossary with terms you are unfamiliar with from the notes above.
    2. Write a program that displays the following pattern using only one println() statement.

      *
      * *
      *   *
      * *
      *

    3. Enhance your compound interest calculator (from Coding Rooms) such that all input and output happens using JOptionPane methods.  You will need to use Dr Java for this.  What output formatting problem do you encounter?  Don’t worry, we’ll learn how to solve this in the future.