Reputation: 1534
hi I know Java for a long time and recently I have been diving deep to the Java world. As an experienced c# developer I find it odd to use Java enum's. For example if I show on console items such as :
public enum AdminOpertionFirstlayer
{MANAGE_SUPPLY,
MANAGE_CUSTOMERS_SERVICE,
ORDERS_MANAGEMENT,
REPORTING_OPRATIONES}
I find it hard to write them down to the user , cause I have to define new varible
*AdminOpertionFirstlayer []adminOpertionFirstlayerArr =
AdminOpertionFirstlayer.values();
in order to achieve this :
for (int i = 0; i < adminOpertionFirstlayerArr.length; i++) {
String s = String.format("%d. %s",
i+1,
adminOpertionFirstlayerArr[i].toString());
Screen.print(s);
}
AdminOpertionFirstlayer chosen= adminOpertionFirstlayerArr
[(Integer.parseInt(dataIn.readLine()))-1];
But I feel it's a bad practice to declare on *
thank you
EDIT
does doing this is understandable and readable ?
public enum MainMenuOptiones{
ADMIN {public void secondLayerMenu(){
Main.AdminSecondLayerMenu();}},
CUSTOMER{public void secondLayerMenu(){
Main.customerSecondLayerMenu();}},
EXIT{public void secondLayerMenu(){
System.exit(1);}},
UNAPPLICABLE{public void secondLayerMenu(){
Screen.printToScreen("chice doesnt exist try again");}};
abstract public void secondLayerMenu();
}
the phrphes is instead of using all the switch mechanism I can use
enumInstance.secondLayerMenu();
Upvotes: 1
Views: 2103
Reputation: 14398
You could use Java's enhanced for loop (and the ordinal value for the enum)
for (AdminOperatorFirstLayer operator : AdminOperatorFirstLayer.values()) {
String s = String.format("%d. %s", operator.ordinal(), operator);
Screen.print(s);
}
Then you can use the ordinal value to recreate the enum:
AdminOperatorFirstLayer chosen =
AdminOperatorFirstLayer.values()[(Integer.parseInt(dataIn.readLine()))];
Or you could use the name:
for (AdminOperatorFirstLayer operator : AdminOperatorFirstLayer.values()) {
String s = String.format("%s. %s", operator.name(), operator);
Screen.print(s);
}
Then you can use valueOf value to recreate the enum:
AdminOperatorFirstLayer chosen =
AdminOperatorFirstLayer.valueOf(dataIn.readLine()];
Upvotes: 5
Reputation: 49331
The Enum<E>
class is the base for all enums in Java.
There's no need to declare a variable with values, use an enhanced for loop to print them out if you want the users to read your source code.
Generally you want to print out a localised string rather than the name of the enum in the source.
There isn't an equivalent to TryParse
, instead use AdminOpertionFirstlayer.valueOf(AdminOpertionFirstlayer.class, string)
and catch the IllegalArgumentException.
Upvotes: 1