1

I have a constants class where I saved HashMaps of constants like:

import java.util.HashMap;
import java.util.Map;

/**
 * Constantes de uso general en el programa.
 */
public final class Consts {

    // Opciones del menu de juego.
    public static final Map<Integer, String> GAMETYPE;
    static
    {
        GAMETYPE = new HashMap<>();
        GAMETYPE.put(1, "MANUAL");
        GAMETYPE.put(2, "AUTOMATIC");
        GAMETYPE.put(3, "EXIT");
    }

    /**
     *
     * @param userType
     * @return
     */
    public static String valueOf(int userType) {
        return GAMETYPE.get(userType);
    }
    /**
     * Impide construir objetos de esta clase.
     */
    private Consts(){
        // Tampoco permite a la clase nativa llamar al constructor.
        throw new AssertionError();
    }
}

I want to use this constants in a switch-case statement in another class like:

userType = sc.nextInt();
switch(Consts.valueOf(userType)) {
    case MANUAL:
        System.out.println(">> You have selected the manual mode");
        break;
    case AUTO:
        System.out.println(">> You have selected the manual mode");
        break;
    case EXIT:
        System.out.println(">> Good-bye");
        break;

Still the program does not find MANUAL, AUTO or EXIT. Any idea?

PS: I do not want to use Enums (this is how I have the constants structured right now but I think that the fact of having many classes for constants makes difficult to follow the code) and I do not want to have the constants declared one by one like:

public static final int MANUAL = 1; 
public static final int AUTO = 2; 
public static final int EXIT = 3; 

as I want the constants to be structured in the constants class. Thanks!

beresfordt
  • 5,088
  • 10
  • 35
  • 43
iusting
  • 7,850
  • 2
  • 22
  • 30

1 Answers1

0

If you are using Java 7 or above, you could do something like:

switch(Consts.valueOf(userType)) {
case "MANUAL"://notice quotes..
    System.out.println(">> You have selected the manual mode");
    break;
case "AUTO":
    System.out.println(">> You have selected the manual mode");
    break;
case "EXIT":
    System.out.println(">> Good-bye");
SMA
  • 36,381
  • 8
  • 49
  • 73
  • I realized I can hard-code the String values in the case, but I wanted to use the values from the HashMap because by using your implementation, if I change the value in the HashMap from let's say MANUAL to MANUAL_MODE , it will not enter the case as the "MANUAL" String and the "MANUAL_MODE" value from the HashMap are not related. – iusting Feb 28 '15 at 11:20
  • In that case define a constant and keep using that same constant reference in both the maps. – SMA Feb 28 '15 at 11:39