Java-11.3 formatted output (1)
In this chapter, we will discuss formatting and output. We will use two chapters to describe this topic.
In the C language system, the most used estimation is the printf function:
printf(%d%f,a,b)
In the preceding simple sentence, formatted output is used. % d indicates the output integer, and % f indicates the floating point number.
1. System. out. printf and System. out. format
Java inherits the C language system, and of course there will be functions such as printf. The following is an example:
package com.ray.ch11;public class Test {public static void main(String[] args) {int a = 1;String b = b;System.out.printf(%d%s, a, b);System.out.println();System.out.format(%d%s, a, b);}}
Output:
1b
1b
In the above Code, System. out. printf and System. out. format are equivalent.
2. Formatter class
Package com. ray. ch11; import java. util. formatter; public class Test {private Formatter formatter = new Formatter (System. out); // The output field public void print (int a, String B) {formatter. format (% d % s, a, B);} public static void main (String [] args) {int a = 1; String B = B; new Test (). print (a, B );}}
Output:
1b
When using the Formatter class, you must note that it must define the output. Otherwise, although the output of the string already exists in memory, there is no output. The above is output on the console, so we put System. out in it.
Summary: This chapter briefly describes two aspects of formatting output: one is the simplest printf function and the other is the Formmater class.