Formatting Output - double amountOwed = cost + tax; //...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Formatting Output Method printf() from the PrintStream Class Sometimes we want to control how output is displayed: o Only 2 places after the decimal point o Printing an integer or a string in a field of a certain width o printf() method: first parameter is a format string that indicates how the output will be formatted o Format string: contains characters that will be printed, and format specifiers o Format specifier: code that starts with a % character and ends with a letter that indicates the format type. o Other printf() parameters: the values to be formatted. Example: double cost = 4.50; final double TAX_RATE = 8.5; // as a percent double tax = cost * TAX_RATE / 100;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: double amountOwed = cost + tax; // print amount owed with 2 places after the decimal point // allow a field of width 5 for the amount System.out.printf("Total owed: %5.2f", amountOwed); Output: Total owed: 4.88 Note: The width of the field is the total number of characters to be printed: one space the digit 4 the decimal point two digits after the decimal point Example: System.out.printf("%-7s%5.2f%n", "Tax:", tax); Now we have 3 format specifiers: %-6s: s indicates a string, the hyphen is a flag which means left alignment, and %n is an end of line specifier...
View Full Document

This note was uploaded on 02/24/2010 for the course C S 305j taught by Professor Staff during the Spring '08 term at University of Texas at Austin.

Page1 / 2

Formatting Output - double amountOwed = cost + tax; //...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online