java formatted strings
Strings of text can be formatted and output with the printf command. The printf command understands a series of characters known as a format specification. It then takes a string of text and formats it, based on the format specification passed over. As an example, supposed we wanted the Output window to display text in neat columns, like this:String heading1 = "Exam_Name";
String heading2 = "Exam_Grade";
System.out.printf( "%-15s %15s %n", heading1,
heading2);
To get the left-justified column, you need a percentage symbol, a minus symbol,
the number of characters, and then the letter "s" (lowercase). So
''%-15s'' means fifteen characters left-justified. To get a right-justified column the same sequence of characters are used, except for the minus sign.
To get a newline %n is used. Note that the characters are surrounded with double quotes.
After a comma, you type the text that you want formatting. The first comma in the code above separates the format specification from the text being formatted.
Here's some tables of the various options.
String Formatting
Integer Formatting
Floating Point Number Formatting
Same as above but the numbers occupy 10 places, with spaces
to the left as padding.
Finally, here's the table again from the start of this formatting section:
In the next section, we'll move on and tackle Java Methods.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment