使用枚举进行迭代的 Java 程序
在本文中,我们将了解如何对枚举对象进行迭代。枚举是一种表示一个较小对象集合的数据类型。
以下是示例 −
输入
假设我们的输入为 −
Enum objects are defined as : red, blue, green, yellow, orange
输出
所需的输出为 −
Printing the Objects: red blue green yellow orange
算法
Step 1 – START Step 2 - Declare the objects of Enum function namely red, blue, green, yellow, orange Step 3 – Using a for loop, iterate over the objects of the enum function and print each object. Step 4- Stop
示例 1
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"); } } }
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
输出
The values of Enum function are previously defined . Accessing each enum constants red blue green yellow orange
示例 2
以下是一个打印星期几的示例。
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)); } }
输出
Values of the enum are: Sunday Monday Tuesday Wednesday Thursday Friday Saturday
广告