How to correctly iterate over all enum values in Java using a for loop?
Hello everyone! I'm a beginner Java developer, and I've encountered a problem when working with enums. \n\nI have an enum for days of the week:\n\n```java\npublic enum Day {\n MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY\n}\n```\n\nI want to print all values of this enum to the console using a for loop. I tried writing this:\n\n```java\nfor (Day day : Day) {\n System.out.println(day);\n}\n```\n\nBut the compiler gives an error: "java: ';' expected" and underlines the enum itself. Then I tried a regular for loop with indices:\n\n```java\nfor (int i = 0; i < Day.length; i++) {\n System.out.println(Day[i]);\n}\n```\n\nThis also gives an error — "cannot find symbol: length". I understand that an enum is not an array or a collection, but how do I iterate over it then? It seems obvious...
No answers yet.
Log in to leave an answer