Formatting Variable Content - Java eLearning Kit For Dummies (2014)

Java eLearning Kit For Dummies (2014)

Chapter 4. Formatting Variable Content

· Displaying output information in a particular way makes it easier for the user to understand.

· Creating a variable for percentages makes it easier for the user to understand some fractional values.

· Relying on escape sequences lets you create specialized line formatting and use special characters.

· Using date and time formatting helps you display these values in the correct time zone and with the user’s locale in mind.

· Specifying currency values using the user’s locale ensures that the output reflects the proper currency symbols, thousands formatting, and decimal formatting.

lingo_fmt.tif

1. Can I define a method for displaying percentages as an integer value, without any decimal?

It’s possible to output a percentage with any number of decimal places, as shown on page 113

2. How can I split a single string value into one or more lines for easier reading?

Use a special escape sequence to split strings into any number of lines or to format them in other ways, as described on page 115

3. Is it possible to create specialized date and time presentations for a specific need?

The date and time formatting provided by Java lets you access each date and time element, such as year or second, to construct special strings, as shown on page 118

4. Are there any limits to the currency formatting that Java provides?

Java won’t automatically convert one currency value to another — it only provides the proper formatting for the currency value, as described on page 124

5. How do I support other human languages in Java?

You describe language-specific features by creating a locale for that language, as described on page 125

Up until now, every application in this book has accepted the default methods of displaying output information. However, Java provides rich methods of formatting output so that it appears as you’d like it to appear, rather than as Java displays it by default. In fact, there are so many techniques that you’ll find them listed throughout the book. The following sections tell you about some basic techniques that you’ll find useful immediately.

Displaying Percentages

A percentage is normally going to appear in your application as a fractional amount in a float or double. Most developers want to display the percentage as a nicely formatted number (one that’s understandable by humans) with a percent sign after it. In the following exercise, you create an application that formats a fractional number as a percentage.

Files needed: DisplayPercent.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.text.NumberFormat;

public class DisplayPercent
{
public static void main(String[] args)
{
// Set the interest rate.
double Interest = .225;

// Create a formatter to use.
NumberFormat Percent =
NumberFormat.getPercentInstance();

// Set the maximum number of digits after the
// decimal point.
Percent.setMaximumFractionDigits(2);

// Try displaying the interest.
System.out.println("The interest is: "
+ Percent.format(Interest));
}
}

The example doesn’t do anything fancy. It begins by creating a double with the percentage rate.

To display a number as a percentage, you need to create a formatter. A formatter is a special class that does nothing but create nice-looking output. In this case, the application creates a NumberFormat object, Percent. Notice that you must call the getPercentInstance() constructor (the method used to construct the object from the class definition) in order to work with percentages.

Java assumes that you want to display percentages as whole numbers. However, you can change this behavior by calling the setMaximumFractionDigits() method. You can also set other values, such as the minimum number of digits used for both the integer and decimal portions of the output.

3. Save the code to disk using the filename DisplayPercent.java.

4. In your command prompt, type javac DisplayPercent.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java DisplayPercent and press Enter.

Figure 4-1 shows the formatted percentage.

9781118098783-fg0401.tif

Figure 4-1:

Using Escape Sequences

When you have some standard text, but you want to format it in a special way, you can use something called an escape character in order to tell Java to perform the formatting. (Here, an escape character means a character that “escapes” from the standard character presentation to do something special, such as move the cursor to the next line.) When you place a number of escape characters together, you get an escape sequence. Escape sequences aren’t unique to Java — many other programming languages use them. In addition, escape sequences have been around for a long time. Even old mainframe systems use escape sequences. So, escape sequences are found on pretty much every platform and they’re standardized across languages for the most part.

An escape character always begins with a backslash (\), followed by a special letter, such as n for creating a new line. Table 4-1 shows the escape characters that Java supports.

Table 4-1 Java Escape Characters

Character

Purpose

Description

\n

New line

Moves the cursor to the next line. Depending on the platform, it may not move the cursor to the beginning of the next line.

\t

Tab

Moves the cursor to the next tab position. Using tabs lets you precisely align output so that it appears as if you’ve used a table to hold the pieces of information.

\b

Backspace

Moves the character back one space without erasing the character on that space. When used correctly, and on the right platform, you can create overstrikes that combine two characters to produce special effects.

\f

Form feed

Ejects the current sheet of paper in a printer and starts fresh with the next sheet.

\”

Double quote

Produces a double quote without ending a quoted element in your code. This escape character is helpful when creating String objects that include a double quote.

\’

Single quote

Produces a single quote without ending a quoted element in your code. This escape character is helpful when creating a char that holds a single quote.

\\

Backslash

Because the backslash is used to create escape characters, you need a special method for including a backslash in your output.

\uDDDD

Unicode character

Produces the specified Unicode character when you provide an appropriate four-digit number. For example, a string that contains "\u00A9" will produce the copyright symbol.


GO ONLINE

It would be nice if everyone used the same character set, but it simply isn’t the case. Consequently, a Unicode character of \u00BD normally produces an output of ½. However, the ASCII text provided at some versions of the Windows command line requires a value of /u00AB to produce the same result. Because different character sets work to different standards, you need to know which character set your application will use when you write it. You can find an incredibly extensive list of these character sets athttp://www.i18nguy.com/unicode/codepages.html.


It’s time to see some of these escape sequences in action. In the following exercise, you create a series of string outputs that rely on escape sequences to produce the desired output. You’ll see many of these escape sequences used in other parts of the book.

Files needed: EscapeCharacters.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

public class EscapeCharacters
{
public static void main(String[] args)
{
// Output various 

// strings using escape 

// sequences.
System.out.println("Use the tab \\t character"
+ "\t to position things on screen.");
System.out.println("Sometimes you want to move"
+ "\nto the next line");

// Replace \u00AB with \u00BD when working with an
// application that actually follows the Unicode
// standard.
System.out.println("The carpenter removed a "
+ "\u00BD\" from the piece of wood.");
}
}

The example uses the escape characters described in Table 4-1 to create sequences that produce a desired output. If you find that the /u00BD escape sequence doesn’t produce the required ½ symbol, change it to /u00AB instead.

3. Match each of the escape characters in the source code to the corresponding entry in Table 4-1 to determine what effect they’ll produce.

It’s essential to see how this code will work in your mind’s eye if you can. After a while, you’ll know from experience how things will look when viewing the escape characters, but it’s helpful to try to figure them out from the outset.

4. Save the code to disk using the filename EscapeCharacters.java.

5. In your command prompt, type javac EscapeCharacters.java and press Enter.

The compiler compiles your application and creates a .class file from it.

6. Type java EscapeCharacters and press Enter.

Figure 4-2 shows the result of using the escape characters.

9781118098783-fg0402.tif

Figure 4-2:

Displaying Date and Time

Java applications will use two distinct methods for working with date and time for the foreseeable future. The older method relies on the Calendar object. A newer method, introduced with Java 8, relies on the date and time API.

Each method has its own way of presenting information to the viewer. The older method is less flexible and requires more code, but it’s the technique you see used in most Java applications today. The newer date and time API provides significant flexibility and offers a range of useful built-in formatting options that require little code. However, because Java 8 is so new, you won’t see this technique used very often just yet. The following sections discuss formatting for both methods.

Using the Calendar object

Most people are quite picky when it comes time to display date and time because the world is a time-oriented place. It’s important to see the date and time presented precisely as expected. The exercise in the “int” section of Chapter 2 exposed you to the Calendar object that provides access to the time and date on your computer. In the following exercise, you create output that matches specific criteria.

Files needed: DisplayDateTime.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.util.Calendar;


public class DisplayDateTime
{
public static void main(String[] args)
{
// Get the current date and time.
Calendar MyCal = Calendar.getInstance();

// Display the date and time on separate lines.
System.out.format("%te %tB %tY",
MyCal, MyCal, MyCal);
System.out.format("\n%tl:%tM %tp",
MyCal, MyCal, MyCal);
}
}

The example begins by creating a Calendar object, MyCal. It then uses a new System.out method, format(), to produce formatted information. The format() method works by using special format codes as placeholders in the string. You then supply a variable to fill each of those placeholders. Table 4-2 describes each of these format codes.

Table 4-2 Example format() Method Formatting Codes

Code

Description

%tB

A locale-specific month name. The month will always appear as a complete name, such as January.

%tb

A locale-specific abbreviated month name, such as Jan for January.

%tm

A two-digit representation of the current month, where January is equal to 01.

%td

A two-digit day of the month without leading zeros. So, the first day of the month will appear as 1.

%te

A two-digit day of the month with leading zeros as needed. So, the first day of the month will appear as 01.

%ty

A two-digit year.

%tY

A four-digit year.

%tA

A locale-specific day of the week name. The day of the week will always appear as a complete name, such as Sunday.

%ta

A locale-specific abbreviated day of the week name, such as Sun for Sunday.

%tD

A shortcut method of outputting the date in %tm%td%ty form.

%tk

The hour using a 24-hour clock without leading zeros. So the first hour will appear as 1.

%tH

The hour using a 24-hour clock with leading zeros as needed. So the first hour will appear as 01.

%tl

The hour using a 12-hour clock without leading zeros. So the first hour will appear as 1.

%tI

The hour using a 12-hour clock with leading zeros as needed. So the first hour will appear as 01.

%tM

The minutes with leading zeros as needed. So the first minute of the hour will appear as 01.

%tS

The seconds with leading zeros as needed. So the first second of the minute will appear as 01.

%tL

The milliseconds with leading zeros as needed. So the first millisecond within the second will appear as 001.

%tN

The nanoseconds with leading zeros as needed. So the first nanosecond within the second will appear as 000000001.

%tp

A locale-specific display of am or pm in lowercase.

%Tp

A locale-specific display of am or pm in uppercase.

%tz

The time zone offset from GMT, such as –0600 for United States Central time.

%tZ

The text time zone value, such as CST for Central Standard Time.

3. Save the code to disk using the filename DisplayDateTime.java.

4. In your command prompt, type javac DisplayDateTime.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java DisplayDateTime and press Enter.

A Calendar object always contains the complete time, so MyCal has everything you need in it. The point is to get the date and time in the form you want them. As shown in Figure 4-3, this example outputs the date and time in a specific format.


LINGO

The term locale refers to someone’s location when it comes to presentation of information. For example, if you live in Kansas, but type all of your documents in German, it’s very likely that you’ll use the German locale. Most people use the locale for the place in which they physically live, but as far as the computer is concerned, locale represents the country’s rules that you use for formatting information such as date, time, numbers, and currency. The locale doesn’t magically translate words into another language.


9781118098783-fg0403.tif

Figure 4-3:

practice_fmt.eps Modify the example as desired to output the time and date in other formats. Try various letter combinations from Table 4-2 to achieve the desired results. After each change to the code, perform steps 3 through 5 so you can see the result on screen.

Using the date and time API

The date and time API is designed to address the date and time handling limitations found in previous versions of Java. Part of the problem for many developers was a lack of formatting flexibility. Yes, you could usually get the output you wanted, but only after working with the code for a long time to get it. The following exercise demonstrates that Java 8 solves the problem of output by providing a number of easy-to-use options.


GO ONLINE

Table 4-2 contains the most common formatting codes. You can create other codes as needed to obtain specific results. The article at http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html provides additional information about date and time formatting.


Files needed: Java8DateTime.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen:

// Import the required API classes.
import java.time.*;
import java.time.format.*;

public class Java8DateTime
{
public static void main(String[] args)
{
// Create a time and date object.
ZonedDateTime theDateTime = ZonedDateTime.now();

// Display some time values.
System.out.println("Local Time: " +
theDateTime.format(
DateTimeFormatter.ISO_LOCAL_TIME));
System.out.println("ISO Offset Time: " +
theDateTime.format(
DateTimeFormatter.ISO_OFFSET_TIME));

// Display a date/time value.
System.out.println("RFC 1123/RFC 822 Date/Time: " +
theDateTime.format(
DateTimeFormatter.RFC_1123_DATE_TIME));

// Display a custom date/time value.
System.out.println("Custom Date/Time: " +
theDateTime.format(
DateTimeFormatter.ofPattern(
"dd MMM yyyy hh:mm:ss a zzzz")));
}
}

The example begins by creating a ZonedDateTime object, theDateTime. A ZonedDateTime object can provide the date and time value using a numeric offset or a variety of named offsets, such as Central Daylight Time or CDT.


GO ONLINE

The example doesn’t even start to show everything that you can do with the ZoneDateTime object in the way of output. The description of the DateTimeFormatter class at http://download.java.net/jdk8/docs/api/java/time/format/DateTimeFormatter.html provides you with additional information.


To output the date and time in a specific way, you need to use the format() method. You provide a formatter as input to this method. In most cases, all you really need is a DateTimeFormatter class object to perform the task. This class provides predefined formatters (such asISO_LOCAL_TIME), or you can describe a format using a pattern. Table 4-3 describes each of these pattern codes.

Table 4-3 Example Patterns

Code

Description

'

Escape for text that would normally be considered a pattern character, such as a single letter a

'' (two single quotes)

Single quote

[

Optional section start

]

Optional section end

a

AM or PM as needed to present the half of a 12-hour day

A

Number of milliseconds in the time value

D

Day of the year

d

Day of the month

E

Day of the week

e/c

Localized day of the week

F

Week of the month

G

Era (such as AD)

h

Hour of the day for a 12-hour clock (1 to 12)

H

Hour of the day for a 24-hour clock (0 to 23)

K

Hour of the day for a 12-hour clock (0 to 11)

k

Hour of the day for a 24-hour clock (1 to 24)

m

Minute of the hour

M/L

Month of the year

n

Nanoseconds of the second

N

Number of nanoseconds in the time value

O

Localized zone-offset

p

Add a padding character

Q/q

Quarter of the year

s

Second of the minute

S

Fraction of the second

u

Year

V

Time zone identifier such as America/Los_Angeles

w

The number of the week in the current year

W

The number of the week in the current month

X

Time zone offset (shows a Z for time zone 0)

x

Time zone offset

y

Year of the current era

Y

Year

z

Time zone name

Z

Time zone offset

3. Save the code to disk using the filename Java8DateTime.java.

4. In your command prompt, type javac Java8DateTime.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java Java8DateTime and press Enter.

This example shows just a few of the available formatting techniques. Figure 4-4 shows typical output. Notice that even though the Zoned
DateTime object can provide a named zone output, it can also provide an offset output.

9781118098783-fg0404.tif

Figure 4-4:

Displaying Currency Values

Displaying monetary amounts is particularly important because a decimal point in the wrong place can cause all kinds of trouble. It’s also important to use the correct symbols. A monetary amount in pounds will definitely differ from one in dollars. In the following example you create locale-specific currency output for a numeric value.

Files needed: DisplayCurrency.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.text.NumberFormat;
import java.util.Locale;
import java.math.BigDecimal;

public class DisplayCurrency
{
public static void main(String[] args)
{
// Set the amount owed.
BigDecimal MyMoney = new BigDecimal("19.95");

// Create a formatter to use.
NumberFormat Currency =
NumberFormat.getCurrencyInstance(Locale.US);

// Try displaying the amount owed.
System.out.println("The amount you owe is: "
+ Currency.format(MyMoney));
}
}

The example begins by creating a monetary value using BigDecimal, which is the recommended way to work with monetary values. MyMoney contains the amount of money that’s owed for this example. However, this value isn’t formatted, so you don’t know whether it’s dollars, pounds, or yen.

The next step creates a NumberFormat, Currency, that’s set up for currency values using getCurrencyInstance(). Notice the use of Locale.US to set the example to output dollars.

3. Save the code to disk using the filename DisplayCurrency.java.

4. In your command prompt, type javac DisplayCurrency.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java DisplayCurrency and press Enter.

The example outputs the value in dollars. Figure 4-5 shows the formatted information.

9781118098783-fg0405.tif

Figure 4-5:

practice_fmt.eps Try changing the code for this example to see the result of different locales. For example, try changing Locale.US to Local.UK to see the output in pounds. The monetary amount won’t change, but the formatting will.

summingup_fmt.eps Summing Up

Here are the key points you learned about in this chapter:

· The NumberFormat object makes it possible to create properly formatted percent output.

· Escape characters make it possible to create nicely formatted output that works on just about every screen.

· Not all platforms use the same character set, so make sure you know which character set your platform uses before working with Unicode character output.

· Make certain that you use locale-specific date and time formatting when working with local times so that features such as month names appear the right way.

· The date and time API provides significantly greater flexibility than using the older Calendar object, but you must have Java 8 to use it.

· Java Currency features will only change the formatting of the output, not the actual value. In other words, Java won’t take your dollar input and convert it to pounds.

Try-it-yourself lab

For more practice with the features covered in this chapter, try the following exercise on your own.

1. Open the EscapeCharacters application.

2. Add code to the application that reproduces the first two columns of Table 4-1.

It helps to think of the positioning that you’ll need to reproduce the table. Use tab and newline characters to carefully reconstruct the table.

3. Compile the application.

4. Run the application.

Check the table you’ve produced for accuracy.

5. Repeat Steps 2 through 4 until your table matches the first two columns of Table 4-1.

6. Repeat Steps 1 through 5 for Table 2-1 found in Chapter 2.

In this case, you need to add the other types of formatting described in this chapter.

Know this tech talk

· constructor: A special method used to build an object from a class description. The constructor contains special code used to perform tasks such as initializing global variables. Every class has a default constructor, even if the code used to create the class doesn’t contain one.

· escape character: A single special control character used to modify the output of an application. For example, the /n escape character adds an additional line between two lines of output.

· escape sequence: Two or more escape characters used to modify the appearance of information on screen. For example, the /t/t escape sequence would add two tabs to the output, which would control the position of text on screen.

· formatter: A special type of class used exclusively for formatting output so it looks nice.

· locale: The characteristics of application output that define a particular language. For example, some languages use a period for the decimal marker, while others use a comma. Formatting data with locale in mind makes it easier for people who speak other languages to use it.