Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - What is a java formatter, what is its function and how to use it?
What is a java formatter, what is its function and how to use it?
Java.util.Formatter is a new class library in JDK 1.5, which is very powerful and mainly used for formatting text.

Formatting is mainly used for text output, such as numbers, dates, amounts and shopping lists and receipts similar to supermarkets, all of which use the tools of print format. Before this class appeared, you could only control the format of the document through space indentation or this tab. Now as long as you master java.util.Formatter, you can use it skillfully.

Examples are as follows:

Import java.util.calendar;

Import java.util.formatter;

Import java.util.gregoriancalendar;

/**

* Formatter test

*

* @ Author Lei Zhimin July 2009-1616: 31:02.

*/

Public class TestFormatter {

Public static void main(String[] args) {

//%[argument _ index $][flags][width][。 Accuracy] conversion

Formatter f 1 = new formatter (system. out);

//Print format strings and numbers

F 1.format ("print format: %s %d", "a",1235);

system . out . println(" \ n-");

//Date format

calendar c = new Gregorian calendar();

F 1.format ("current date:%1$ ty-%1$ tm-%1$ te", c);

system . out . println(" \ n-");

//Format the date and store the formatted result in a string variable.

String s = String.format ("current date:%1$ ty-%1$ tm-%1$ te", c);

system . out . println(s);

//2$: Take the second parameter.

//-:Specifies left alignment, and the default is right alignment.

//5: The maximum output width is 20. If it is not enough, the spaces will be filled. If it really exceeds, it will be all output.

//.2: This indicates the maximum number of characters of output parameter 2. If it is a floating-point number, it indicates the number of digits displayed in the decimal part.

//s: indicates that the input parameter is a string.

f 1 . format(" % 2 $-5.2s % 1 $ 2s "," 123 "," 456 ");

//Store the formatted result in a string.

system . out . println(" \ n-");

String fs = String.format ("height and weight (%). 2f, %d)",173.2,65);

system . out . println(fs);

//printf () essentially constructs a Formatter object with System.out as the output target.

//Call the format method and pass the parameters of printf to the format method.

system . out . println(" \ n-");

System.out.printf ("height and weight (%). 2f, %d",180.2,65);

}

}

Running results:

Print format: a 1235

-

Current date: July 2009-16

-

Current date: July 2009-16

45 123

-

Height and weight (173.20,65)

-

Height and weight (180.20,65)

Process ends with exit code 0.