I want to get the enum value by name string,
this the enum code: package practice;
enum Mobile {
Samsung(400),
Nokia(250),
Motorola(325);
int pr
You can use something like:
final Mobile mobile = Mobile.valueOf("Samsung");
final int price = mobile.showPrice();
(you do have to change the scope of the method showPrice()
to public
).
as you may know, there is a valueOf method in every enum, which returns the constant just by resolving the name(read about exceptions when the string is invalid.)
now, since your enum has another fields associated to the constants you need to search its value by matching those fields too...
this is a possible solution using
public enum ProgramOfStudy {
ComputerScience("CS"),
AutomotiveComputerScience("ACS"),
BusinessInformatics("BI");
public final String shortCut;
ProgramOfStudy(String shortCut) {
this.shortCut = shortCut;
}
public static ProgramOfStudy getByShortCut(String shortCut) {
return Arrays.stream(ProgramOfStudy.values()).filter(v -> v.shortCut.equals(shortCut)).findAny().orElse(null);
}
}
so you can "resolve" the enum by searching its "shortcut"
like
System.out.println(ProgramOfStudy.getByShortCut("CS"));