- public class Main
- {
- publicstaticvoid main(String[] args)
- {
- // Define some variables to format the output.
- double d = 345.678;
- String s = "Hello!" ;
- int i = 1234;
- // "%" means formatted output, and the content after "%" is the definition of the format.
- System.out.printf( "%f" , d); // "f" means formatted output float.
- System.out.println();
- System.out.printf( "%9.2f" , d); // The 9 in "9.2" is the length of the output, and the 2 is the number of digits after the decimal point.
- System.out.println();
- System.out.printf( "%+9.2f" , d); // "+" means the output number is signed.
- System.out.println();
- System.out.printf( "%-9.4f" , d); // "-" means that the output number is left-aligned (default is right-aligned).
- System.out.println();
- System.out.printf( "%+-9.3f" , d); // "+-" means the output number is signed and left justified.
- System.out.println();
- System.out.printf( "%d" , i); // "d" means output decimal integer.
- System.out.println();
- System.out.printf( "%o" , i); // "o" means output octal integer.
- System.out.println();
- System.out.printf( "%x" , i); // "d" means output hexadecimal integer.
- System.out.println();
- System.out.printf( "%#x" , i); // "d" means output an integer with a hexadecimal flag.
- System.out.println();
- System.out.printf( "%s" , s); // "d" means output string.
- System.out.println();
- System.out.printf( "Output a float: %f, an integer: %d, a string: %s" , d, i, s);
- // Multiple variables can be output, pay attention to the order.
- System.out.println();
- System.out.printf( "String: %2$s, hexadecimal number of %1$d: %1$#x" , i, s);
- // "X$" represents the number of variables.
- }
- }
How to use java system.out.printf() [transfer]
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326238162&siteId=291194637
Ranking