Java Switch on Enum Value

  • A+
Category:Languages

I want the user to enter a number from 1 to 7. If the number is 1, print that it is a Monday. If the number is 2, print that it is Tuesday, etc.

The following code compiles, but it is not logically correct.

Please see the comments for where assistance is required:

import java.util.Scanner;  public class Test {     private enum Week {         MONDAY("1"), TUESDAY("2"), WEDNESDAY("3"),          THURSDAY("4"), FRIDAY("5"), SATURDAY("6"), SUNDAY("7");         private String value;          private Week(String value) {             this.value = value;         }     }      public static void main(String[] args) {          // How to instantiate this correctly, so that it doesn't only point to one value         Week week = Week.MONDAY;         System.out.print("Enter a number: ");         Scanner input = new Scanner(System.in);         String userInput = input.next();          // The switch parameter is not correct. This is what needs to be fixed.         // I want to use this case layout.         //The enums each have a value. The user enters a value. I want to switch over userInput.         switch (week) {             case MONDAY: System.out.println("That's Monday"); break;             case TUESDAY: System.out.println("That's Tuesday"); break;             case WEDNESDAY: System.out.println("That's Wednesday"); break;             case THURSDAY: System.out.println("That's Thursday"); break;             case FRIDAY: System.out.println("That's Friday"); break;             case SATURDAY: System.out.println("That's Saturday"); break;             case SUNDAY: System.out.println("That's Sunday"); break;             default: break;         }     } } 

 


You need to introduce a method to fetch the enum constant based on the value passed in :

public static Week fetchValue(String constant) {     Week weekday = null;     for (Week week : Week.values()) {         if (week.value.equals(constant)) {             weekday = week;         }     }     return weekday; } 

Now use it like :

Week weekday = Week.fetchValue(userInput); if (weekday != null) {    switch (week ) {      // rest of the code     } } else {    System.out.println("Incorrect input"); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: