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

โปรแกรม Java พิมพ์คำที่มีความยาวเป็นเลขคู่


บทนำ

ในบทความนี้ เราจะเรียนรู้วิธีการพิมพ์คำ (Words) ที่มีความยาวเป็นเลขคู่ (Even length) สตริงเป็นชนิดข้อมูลที่ประกอบด้วยตัวอักษรหนึ่งตัวขึ้นไป และล้อมรอบด้วยเครื่องหมายคำพูดคู่ (" ") Char เป็นชนิดข้อมูลที่ประกอบด้วยอักษรหรือตัวเลขหรืออักขระพิเศษ

ตัวอย่างการทำงาน

อินพุทตัวอย่าง:

Input string: Java Programming are cool

เอาต์พุทที่คาดหวัง:

The words with even lengths are: Java cool

อัลกอริทึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศสตริง input_string
ขั้นตอนที่ 3 - กำหนดค่า
ขั้นตอนที่ 4 - วนลูปผ่านสตริง คำนวณ word.length() % 2 สำหรับแต่ละคำ ตรวจสอบว่าหาร 2 ลงตัว
ขั้นตอนที่ 5 - แสดงผลลัพธ์
ขั้นตอนที่ 6 - จบการทำงาน

ตัวอย่างที่ 1: เขียนในฟังก์ชัน main โดยตรง

public class EvenLengths {
    public static void main(String[] args) {
        String input_string = "Java Programming are cool";
        System.out.println("The string is defined as: " + input_string);
        System.out.println("\nThe words with even lengths are: ");
        for (String word : input_string.split(" ")) {
            if (word.length() % 2 == 0) {
                System.out.println(word);
            }
        }
    }
}

เอาต์พุท

The string is defined as: Java Programming are cool
The words with even lengths are: Java cool

ตัวอย่างที่ 2: ใช้เมธอดแยก (Object-Oriented Style)

public class EvenLengths {
    public static void printWords(String input_string) {
        System.out.println("\nThe words with even lengths are: ");
        for (String word : input_string.split(" ")) {
            if (word.length() % 2 == 0) {
                System.out.println(word);
            }
        }
    }
    
    public static void main(String[] args) {
        String input_string = "Java Programming are cool";
        System.out.println("The string is defined as: " + input_string);
        printWords(input_string);
    }
}

เอาต์พุท

The string is defined as: Java Programming are cool
The words with even lengths are: Java cool

ขยายความสามารถ:

// ใช้ Stream API (Java 8+)
public static void printEvenWords(String input) {
    Arrays.stream(input.split("\\s+"))
          .filter(w -> w.length() % 2 == 0)
          .forEach(System.out::println);
}

// รองรับเครื่องหมายวรรคตอน
public static void printEvenWordsRobust(String input) {
    Pattern pattern = Pattern.compile("\\b\\w+\\b");
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        String word = matcher.group();
        if (word.length() % 2 == 0) System.out.println(word);
    }
}