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

โปรแกรม Java วนลูป Enum (Iterate over Enum)

ในบทความนี้ เราจะเรียนรู้วิธีวนลูปเข้าถึงค่า Enum ในภาษา Java Enum เป็นชนิดข้อมูลที่แทนกลุ่มค่าคงที่เล็กๆ

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

อินพุต:

Enum objects are defined as: red, blue, green, yellow, orange

เอาต์พุต:

Printing the Objects:
red
blue
green
yellow
orange

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศค่าคงที่ Enum: red, blue, green, yellow, orange
  3. ใช้ลูป for-each วนเข้าถึงแต่ละค่าของ Enum และพิมพ์ออกมา
  4. จบโปรแกรม

ตัวอย่างที่ 1: Enum พื้นฐาน

enum Enum {
    red, blue, green, yellow, orange;
}

public class Colour {
    public static void main(String[] args) {
        System.out.println("The values of Enum function are previously defined.");
        System.out.println("Accessing each enum constants");
        for (Enum colours : Enum.values()) {
            System.out.print(colours + "\n");
        }
    }
}

ตัวอย่างที่ 2: ใช้ EnumSet สำหรับวันในสัปดาห์

import java.util.EnumSet;

enum Days {
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}

public class IterateEnum {
    public static void main(String args[]) {
        Days my_days[] = Days.values();
        System.out.println("Values of the enum are:");
        EnumSet.allOf(Days.class).forEach(day -> System.out.println(day));
    }
}

ตัวอย่างที่ 1 ใช้ Enum.values() แบบคลาสสิก ตัวอย่างที่ 2 ใช้ EnumSet.allOf() ร่วมกับ lambda expression ซึ่งเป็นวิธีทันสมัยกว่า