Niekedy je pri programovaní nevyhnutné vytlačiť výstup v danom špecifikovanom formáte. Väčšina používateľov pozná funkciu printf v jazyku C. V tomto článku si rozoberieme, ako môžeme formátovať výstup pomocou printf() v Jave.
Formátovanie pomocou Java Printf()
printf() používa na formátovanie špecifikátory formátu. Existujú určité typy údajov, ktoré sú uvedené nižšie:
- Pre formátovanie čísel
- Formátovanie desatinných čísel
- Pre boolovské formátovanie
- Pre formátovanie reťazca
- Pre formátovanie znakov
- Pre formátovanie dátumu a času
i). Pre formátovanie čísel
Samotné číslo obsahuje Integer, Long atď. Použitý špecifikátor formátovania je %d.
prepojený zoznam v jazyku Java
Nižšie je uvedená implementácia vyššie uvedenej metódy:
Java
// Java Program to demonstrate> // Use of printf to> // Formatting Integer> import> java.io.*;> > // Driver Class> class> GFG {> > // main function> > public> static> void> main (String[] args) {> > int> a=> 10000> ;> > > //System.out.printf('%.d%n',a);> > System.out.printf(> '%,d%n'> ,a);> > }> }> |
>
>Výkon
10,000>
ii). Pre formátovanie desatinných čísel
Formátovanie desatinných čísel je možné vykonať pomocou funkcie print() a špecifikátora formátu %f.
Nižšie je uvedená implementácia vyššie uvedenej metódy:
Java
// Java Programs to demonstrate> // Use of Printf() for decimal> // Number Formatting> import> java.io.*;> > // Driver Class> class> GFG {> > // main function> > public> static> void> main(String[] args)> > {> > // declaring double> > double> a => 3.14159265359> ;> > > // Printing Double Value with> > // different Formatting> > System.out.printf(> '%f
'> , a);> > System.out.printf(> '%5.3f
'> , a);> > System.out.printf(> '%5.2f
'> , a);> > }> }> |
>
>Výkon
3.141593 3.142 3.14>
iii). Pre boolovské formátovanie
Booleovské formátovanie je možné vykonať pomocou printf a ( '%b' alebo '%B') v závislosti od požadovaného výsledku.
Nižšie je uvedená implementácia vyššie uvedenej metódy:
Java
// Java Programs to demonstrate> // Use of Printf() for decimal> // Boolean Formatting> import> java.io.*;> > // Driver Function> class> GFG {> > // main function> > public> static> void> main(String[] args)> > {> > int> a => 10> ;> > Boolean b => true> , c => false> ;> > Integer d => null> ;> > > // Fromatting Done using printf> > System.out.printf(> '%b
'> , a);> > System.out.printf(> '%B
'> , b);> > System.out.printf(> '%b
'> , c);> > System.out.printf(> '%B
'> , d);> > }> }> |
>
číslo palindrómu
>Výkon
true TRUE false FALSE>
iv). Pre formátovanie znakov
Formátovanie znakov je ľahko pochopiteľné, pretože vyžaduje printf() a použité špecifikátory formátu znakov sú „%c“ a „%C“.
Nižšie je uvedená implementácia vyššie uvedenej metódy:
Java
// Java Program to Formatt> //> import> java.io.*;> > // Driver Class> class> GFG {> > // main function> > public> static> void> main(String[] args)> > {> > char> c => 'g'> ;> > > // Formatting Done> > System.out.printf(> '%c
'> , c);> > > // Converting into Uppercase> > System.out.printf(> '%C
'> , c);> > }> }> |
>
>Výkon
g G>
v). Pre formátovanie reťazca
Formátovanie reťazcov vyžaduje znalosť reťazcov a použitého špecifikátora formátu „%s“ a „%S“.
Nižšie je uvedená implementácia vyššie uvedenej metódy:
Java
// Java Program to implement> // Printf() for String Formatting> import> java.io.*;> > // Driver Class> class> GFG {> > // main function> > public> static> void> main(String[] args)> > {> > String str => 'geeksforgeeks'> ;> > > // Formatting from lowercase to> > // Uppercase> > System.out.printf(> '%s
'> , str);> > System.out.printf(> '%S
'> , str);> > > str => 'GFG'> ;> > // Vice-versa not possible> > System.out.printf(> '%S
'> , str);> > System.out.printf(> '%s
'> , str);> > }> }> |
herec govinda
>
>Výkon
geeksforgeeks GEEKSFORGEEKS GFG GFG>
vi). Pre formátovanie dátumu a času
Formátovanie dátumu a času nie je také jednoduché ako typ údajov použitý vyššie. Využíva viac než len jednoduchý formát špecifikátor znalosti možno pozorovať v príklade uvedenom nižšie.
Nižšie je uvedená implementácia vyššie uvedenej metódy:
Java
// Java Program to demonstrate use of> // printf() for formatting Date-time> import> java.io.*;> import> java.util.*;> > // Driver Class> class> GFG {> > // main function> > public> static> void> main(String[] args)> > {> > Date time => new> Date();> > > System.out.printf(> 'Current Time: %tT
'> , time);> > > // Another Method with all of them Hour> > // minutes and seconds seperated> > System.out.printf(> 'Hours: %tH Minutes: %tM Seconds: %tS
'> ,> > time,time, time);> > > // Another Method to print the time> > // Followed by am/pm , time in milliseconds> > // nanoseconds and time-zone offset> > System.out.printf(> '%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n'> ,> > time);> > }> }> |
>
>Výkon
Current Time: 11:32:36 Hours: 11 Minutes: 32 Seconds: 36 11:32:36 am 198 198000000 +0000>
Poznámka: System.out.format() je ekvivalentný s printf() a možno ho tiež použiť.
Ďalšie spôsoby formátovania
1. Formátovanie pomocou triedy DecimalFormat
DecimalFormat sa používa na formátovanie desatinných čísel.
Nižšie je uvedená implementácia vyššie uvedenej metódy:
Java
// Java program to demonstrate working of DecimalFormat> import> java.text.DecimalFormat;> > // Driver Class> class> JavaFormatter2 {> > // main function> > public> static> void> main(String args[])> > {> > double> num => 123.4567> ;> > > // prints only numeric part of a floating number> > DecimalFormat ft => new> DecimalFormat(> '####'> );> > System.out.println(> 'Without fraction part: num = '> > + ft.format(num));> > > // this will print it upto 2 decimal places> > ft => new> DecimalFormat(> '#.##'> );> > System.out.println(> 'Formatted to Give precision: num = '> > + ft.format(num));> > > // automatically appends zero to the rightmost part> > // of decimal instead of #,we use digit 0> > ft => new> DecimalFormat(> '#.000000'> );> > System.out.println(> 'appended zeroes to right: num = '> > + ft.format(num));> > > // automatically appends zero to the leftmost of> > // decimal number instead of #,we use digit 0> > ft => new> DecimalFormat(> '00000.00'> );> > System.out.println(> 'formatting Numeric part : num = '> > + ft.format(num));> > > // formatting money in dollars> > double> income => 23456.789> ;> > ft => new> DecimalFormat(> '$###,###.##'> );> > System.out.println(> 'your Formatted Dream Income : '> > + ft.format(income));> > }> }> |
>
>Výkon
Without fraction part: num = 123 Formatted to Give precision: num = 123.46 appended zeroes to right: num = 123.456700 formatting Numeric part : num = 00123.46 your Formatted Dream Income : ,456.79>
2. Formátovanie dátumov a analýza pomocou triedy SimpleDateFormat
Táto trieda je prítomná v balíku java.text.
Nižšie je uvedená implementácia vyššie uvedenej metódy:
Java
// Java program to demonstrate working of SimpleDateFormat> import> java.text.ParseException;> import> java.text.SimpleDateFormat;> import> java.util.Date;> > // Driver Class> class> Formatter3 {> > // main function> > public> static> void> main(String args[])> > throws> ParseException> > {> > // Formatting as per given pattern in the argument> > SimpleDateFormat ft> > => new> SimpleDateFormat(> 'dd-MM-yyyy'> );> > > String str = ft.format(> new> Date());> > System.out.println(> 'Formatted Date : '> + str);> > > // parsing a given String> > str => '02/18/1995'> ;> > ft => new> SimpleDateFormat(> 'MM/dd/yyyy'> );> > Date date = ft.parse(str);> > > // this will print the date as per parsed string> > System.out.println(> 'Parsed Date : '> + date);> > }> }> |
reťazec.obsahuje java
>
>Výkon
Formatted Date : 24-01-2022 Parsed Date : Sat Feb 18 00:00:00 UTC 1995>