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!
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.