Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีพิมพ์ข้อความจัดรูปแบบด้วย printf() ใน Java


printf() ใช้จัดรูปแบบ output ให้ java.io.PrintStream หรือ java.io.PrintWriter คลาสเหล่านี้มีเมธอด format() ให้ผลเหมือนกัน ดังนั้นสิ่งที่อ่านได้สำหรับ printf() ใช้กับ format() ได้เช่นกัน

ไวยากรณ์

System.out.printf("format-string" [, arg1, arg2, ... ]);

ตัวอย่าง 1

import java.io.PrintStream;

public class PrintfTest1 {
    public static void main(String[] args) {
        int i = 1234;
        System.out.printf("Decimal: %1$,d Octal: %1$o Hex: %1$x\n", i);
        String str = "Tutorials Point";
        System.out.printf("%15s", str);
    }
}

ผลลัพธ์

Decimal: 1,234 Octal: 2322 Hex: 4d2 Tutorials Point

ตัวอย่าง 2

public class PrintfTest2 {
    public static void main(String[] args) {
        String name = "Adithya";
        int age = 30;
        System.out.format("%-10s - %4d\n", name, age);
    }
}

ผลลัพธ์

Adithya     -    30