Lesson 1.4c -
Formatted Output An EasyFormat method call is used in conjunction with a System.out.print or System.out.println statement. The basic structure is as follows: System.out.println(EasyFormat.format(data, width)); In the example above, data can be a variable or value of any type except double. The width must be an integer or an integer variable. For example, if the programmer desired to print an integer variable num in a width of 5, the statement would be System.out.println(EasyFormat.format(num, 5)); So what is the result? Suppose that the value of num is 352. That is a 3-digit number, so specifying a width of 5 will mean that there will be two blank spaces displayed before the number. Let's see another example. int num1 = 352, num2 = 1234; The above statements will produce the following output: 352 Note that the use of a width of 6 in both format calls makes the numbers line up on the right side, causing them to align on place value. The output gives 3 spaces before the 352 and 2 spaces before the 1234. Another example: String word = "Wins"; The above statements will produce the following output: Wins The use of different widths here produced a "centering" effect with the word and the number. Also, there were 2 spaces printed before "Wins" since it has 4 characters and the width was 6. There were 3 spaces printed before 32 since it has two digits and the width was 5. Formatting the output of a double To display a double with the EasyFormat class, it is necessary to provide additional information to determine the number of decimal places to show. Some examples follow. double number = 12.3456; The above statements will produce the following output: 12.3 Note that when specifying decimal places, the resulting display rounds to that number of decimal places. Also, it is important to know that the decimal point takes up a space in the width. So 12.3 takes up 4 overall characters, with 4 spaces printed before it for a total width of 8 characters displayed. Click here for more examples of the EasyFormat Class. In Closing Only use the EasyFormat class when formatted output is called for in a program. Otherwise, just use the basic print and println statements. The EasyFormat class description is in your classes folder. There is no need to declare anything when using it. Just use it as shown in the examples above. |
|||||||||||
© DanShuster.com