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

การพิมพ์ตัวแปรเดี่ยวและหลายตัวใน Java (printf, println)

ตัวอย่าง: พิมพ์ตัวแปรหลายแบบ

public class Demo {
    public static void main(String[] args) {
        String firstName = "Hello";
        String lastName = "World";
        
        // 1. println - เรียบง่าย
        System.out.println("Printing single variable");
        System.out.println(firstName);
        
        // 2. printf - จัดรูปแบบ (format string)
        System.out.println("\nPrinting multiple variables with printf");
        System.out.printf("First Name: %s%nLast Name: %s%n", firstName, lastName);
        
        // 3. String.format - สร้างสตริง formatted
        String formatted = String.format("Name: %s %s", firstName, lastName);
        System.out.println("\nUsing String.format: " + formatted);
        
        // 4. ตัวเลขและ formatting
        int num = 42;
        double pi = 3.14159;
        System.out.printf("Number: %d, Pi: %.2f, Hex: %x%n", num, pi, num);
    }
}

ผลลัพธ์

Printing single variable
Hello

Printing multiple variables with printf
First Name: Hello
Last Name: World

Using String.format: Name: Hello World
Number: 42, Pi: 3.14, Hex: 2a

Format Specifiers พื้นฐาน

Specifierคำอธิบายตัวอย่าง
%sString"Hello"
%dInteger (decimal)42
%fFloating point3.14159
%.2fFloat 2 ตำแหน่งทศนิยม3.14
%xHexadecimal (lowercase)2a
%nNewline (platform-independent)-
%bBooleantrue/false

แนวทางเลือก

  • พิมพ์ง่ายๆ: System.out.println() หรือ System.out.print()
  • ต้องจัดรูปแบบ: System.out.printf() หรือ String.format()
  • ประสิทธิภาพ: StringBuilder + append() สำหรับต่อสตริงมาก