Java

printf

soheedev 2023. 9. 8. 19:21

System.out.printf(format, arguments)

 

format

  • %n : 줄바꿈
  • %s : String 형식으로 출력
  • %d : integer 형식으로 출력
  • %f : float 형식으로 출력
  • %t : date, time 형식으로 출력
  • %o : 8진수 integer 형식으로 출력
  • %x : 16진수 integer 형식으로 출력
  • %b : boolean 형식으로 출력
  • %e : 지수 형식으로 출력
long n = 461012;
System.out.format("%d%n", n);      //  -->  "461012"
System.out.format("%08d%n", n);    //  -->  "00461012"
System.out.format("%+8d%n", n);    //  -->  " +461012"
System.out.format("%,8d%n", n);    // -->  " 461,012"
System.out.format("%+,8d%n%n", n); //  -->  "+461,012"

double pi = Math.PI;
System.out.format("%f%n", pi);       // -->  "3.141593"
System.out.format("%.3f%n", pi);     // -->  "3.142"
System.out.format("%10.3f%n", pi);   // -->  "     3.142"
System.out.format("%-10.3f%n", pi);  // -->  "3.142     "
System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi); // -->  "3,1416"

Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // -->  "May 29, 2006"
System.out.format("%tl:%tM %tp%n", c, c, c);  // -->  "2:34 am"
System.out.format("%tD%n", c);    // -->  "05/29/06"
 
Scanner sc=new Scanner(System.in);

System.out.println("================================");

for(int i=0;i<3;i++){
    String s1=sc.next();
    int x=sc.nextInt();

    System.out.format("%-15s", s1);
    System.out.printf("%03d%n", x);
}

System.out.println("================================");
Sample Input

java 100
cpp 65
python 50

Sample Output
================================
java 100
cpp 065
python 050
================================

 

'Java' 카테고리의 다른 글

Scanner 클래스  (0) 2023.09.08