1. Pengenalan
Dalam tutorial ini, kami akan menunjukkan contoh yang berbeza pemformatan dengan printf () kaedah .
Kaedahnya adalah sebahagian daripada kelas java.io.PrintStream dan menyediakan format String yang serupa dengan fungsi printf () di C.
2. Sintaks
Kita dapat menggunakan salah satu kaedah PrintStream berikut untuk memformat output:
System.out.printf(format, arguments); System.out.printf(locale, format, arguments);
Kami menentukan peraturan pemformatan menggunakan parameter format . Peraturan bermula dengan watak '%' .
Mari kita lihat contoh ringkas sebelum kita mengetahui perincian pelbagai peraturan pemformatan:
System.out.printf("Hello %s!%n", "World");
Ini menghasilkan output berikut:
Hello World!
Seperti yang ditunjukkan di atas, string format mengandungi teks biasa dan dua peraturan pemformatan. Peraturan pertama digunakan untuk memformat argumen rentetan. Peraturan kedua menambah watak barisan baru di hujung rentetan.
2.1. Peraturan Format
Mari kita lihat rentetan format dengan lebih dekat. Ia terdiri daripada penentu literal dan format. Penentu format merangkumi bendera, lebar, ketepatan, dan watak penukaran dalam urutan berikut:
%[flags][width][.precision]conversion-character
Penentu dalam kurungan adalah pilihan.
Secara dalaman, printf () menggunakan kelas java.util.Formatter untuk menguraikan rentetan format dan menghasilkan output. Pilihan rentetan format tambahan boleh didapati di Formatter Javadoc.
2.2. Watak Penukaran
The penukaran aksara diperlukan dan menentukan bagaimana hujah diformat . Aksara penukaran hanya sah untuk jenis data tertentu. Beberapa perkara biasa adalah:
- s - rentetan format
- d - format bilangan bulat perpuluhan
- f - membentuk nombor titik terapung
- t - format nilai tarikh / masa
Kami akan menerangkannya dan beberapa yang lain kemudian dalam artikel.
2.3. Pengubah Pilihan
The [bendera] menentukan cara standard untuk mengubah suai output dan adalah yang paling biasa untuk memformat integer dan terapung nombor titik.
[Lebar] menentukan lebar medan untuk mengeluarkan argumen. Ini mewakili bilangan watak minimum yang ditulis untuk output.
[.Precision] menentukan bilangan digit ketepatan ketika mengeluarkan nilai floating-point. Selain itu, kita dapat menggunakannya untuk menentukan panjang substring untuk diekstrak dari String .
3. Pemisah Garis
Untuk memecahkan rentetan menjadi garis berasingan, kami mempunyai penentu % n :
System.out.printf("baeldung%nline%nterminator");
Coretan kod di atas akan menghasilkan output berikut:
baeldung line terminator
The % n pemisah printf () secara automatik akan memasukkan pemisah talian speakers sistem tuan rumah itu .
4. Pemformatan Boolean
Untuk memformat nilai boolean, kami menggunakan format % b . Ia berfungsi dengan cara berikut: Sekiranya nilai input benar , outputnya benar . Jika tidak, outputnya salah .
Jadi, jika kita melakukan:
System.out.printf("%b%n", null); System.out.printf("%B%n", false); System.out.printf("%B%n", 5.3); System.out.printf("%b%n", "random text");
Kemudian kita akan melihat:
false FALSE TRUE true
Perhatikan bahawa kita dapat menggunakan % B untuk pemformatan huruf besar.
5. Pemformatan Rentetan
Untuk memformat rentetan mudah, kami akan menggunakan kombinasi % s . Selain itu, kita boleh menjadikan rentetan huruf besar:
printf("'%s' %n", "baeldung"); printf("'%S' %n", "baeldung");
Dan outputnya adalah:
'baeldung' 'BAELDUNG'
Juga, untuk menentukan panjang minimum, kita dapat menentukan lebar :
printf("'%15s' %n", "baeldung");
Yang memberi kita:
' baeldung'
Sekiranya kita perlu membiarkan-membenarkan rentetan kita, kita boleh menggunakan bendera '-' :
printf("'%-10s' %n", "baeldung");
Dan outputnya adalah:
'baeldung '
Even more, we can limit the number of characters in our output by specifying a precision:
System.out.printf("%2.2s", "Hi there!");
The first ‘x' number in %x.ys syntax is the padding. ‘y' is the number of chars.
For our example here, the output is Hi.
6. Char Formatting
The result of %c is a Unicode character:
System.out.printf("%c%n", 's'); System.out.printf("%C%n", 's');
The capital letter C will uppercase the result:
s S
But, if we give it an invalid argument, then Formatter will throw IllegalFormatConversionException.
7. Number Formatting
7.1. Integer Formatting
The printf() method accepts all the integers available in the language; byte, short, int, long and BigInteger if we use %d:
System.out.printf("simple integer: %d%n", 10000L);
With the help of the ‘d' character, we'll have:
simple integer: 10000
In case we need to format our number with the thousands separator, we can use the ‘,'flag. And we can also format our results for different locales:
System.out.printf(Locale.US, "%,d %n", 10000); System.out.printf(Locale.ITALY, "%,d %n", 10000);
As we see, the formatting in the US is different than in Italy:
10,000 10.000
7.2. Float and Double Formatting
To format a float number, we'll need the ‘f' format:
System.out.printf("%f%n", 5.1473);
Which will output:
5.147300
Of course, the first thing that comes to mind is to control the precision:
System.out.printf("'%5.2f'%n", 5.1473);
Here we define the width of our number as 5, and the length of the decimal part is 2:
' 5.15'
Here we have one space padding from the beginning of the number to support the predefined width.
To have our output in scientific notation, we just use the ‘e' conversion character:
System.out.printf("'%5.2e'%n", 5.1473);
And the result is the following:
'5.15e+00'
8. Date and Time Formatting
For date and time formatting, the conversion string is a sequence of two characters: the ‘t' or ‘T' character and the conversion suffix. Let's explore the most common time and date formatting suffix characters with the examples.
Definitely, for more advanced formatting we can use DateTimeFormatter which has been available since Java 8.
8.1. Time Formatting
First, let's see the list of some useful suffix characters for Time Formatting:
- ‘H', ‘M', ‘S' – characters are responsible for extracting the hours, minutes and second from the input Date
- ‘L', ‘N' – to represent the time in milliseconds and nanoseconds accordingly
- ‘p' – adds am/pm formatting
- ‘z' – prints out the timezone offset
Now, let's say we wanted to print out the time part of a Date:
Date date = new Date(); System.out.printf("%tT%n", date);
The code above along with ‘%tT' combination produces the following output:
13:51:15
In case we need more detailed formatting, we can call for different time segments:
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
Having used ‘H', ‘M', and ‘S' we get:
hours 13: minutes 51: seconds 15
Though, listing date multiple times is a pain. Alternatively, to get rid of multiple arguments, we can use the index reference of our input parameter which is 1$ in our case:
System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);
Here we want as an output the current time, am/pm, time in milliseconds, nanoseconds and the timezone offset:
13:51:15 pm 061 061000000 +0400
8.2. Date Formatting
Like time formatting, we have special formatting characters for date formatting:
- ‘A' – prints out the full day of the week
- ‘d' – formats a two-digit day of the month
- ‘B' – is for the full month name
- ‘m' – formats a two-digit month
- ‘Y' – outputs a year in four digits
- ‘y' – outputs the last two digits of the year
So, if we wanted to show the day of the week, followed by the month:
System.out.printf("%1$tA, %1$tB %1$tY %n", date);
Then using ‘A', ‘B', and ‘Y', we'd get:
Thursday, November 2018
To have our results all in numeric format, we can replace the ‘A', ‘B', ‘Y ‘ letters with ‘d', ‘m', ‘y':
System.out.printf("%1$td.%1$tm.%1$ty %n", date);
Which will result in:
22.11.18
9. Summary
Dalam artikel ini, kami membincangkan cara menggunakan kaedah PrintStream # printf untuk memformat output. Kami melihat corak format yang berbeza yang digunakan untuk mengawal output untuk jenis data biasa.
Akhirnya, seperti biasa, kod yang digunakan semasa perbincangan boleh didapati di GitHub.