I created this enum:
public enum CoffeeSorts {
Coffee("Kaffee"), Espresso("Espresso"), Mocca("Mocca"), Cappuccino(
"Cappuccino"), LatteMacchiato("Latte Macchiato"), DoubleEspresso(
"doppelter Espresso");
private final String stringValue;
private CoffeeSorts(final String s) {
stringValue = s;
}
public String toString() {
return stringValue;
}
}
I tried the following way to use it
public ACoffee createCoffee(String type) {
switch (type) {
case CoffeeSorts.Cappuccino :
try {
return new ChocolateSprincles(new Cream(new Coffee()));
} catch (Exception e) {}
return null;
break;
case CoffeeSorts.LatteMacchiato :
try {
return new ...
}
.
.
.
}
It only gives me an Error saying "cannot convert from CoffeeSorts to String". Can you tell me what i did wrong?
Your type
variable is a String
, but you're trying to specify values which are CoffeeSort
values. You'll need to convert the String
to a CoffeeSort
first, or change the signature.
For example:
public ACoffee createCoffee(CoffeeSort type) {
...
}
or
public ACoffee createCoffee(String typeName) {
CoffeeSort type = CoffeeSort.valueOf(typeName);
...
}
Also note that you can't break;
after a return
statement, as it's unreachable code. (I hope your exception handling isn't really like that, either...)
Finally, consider changing your code entirely to put a createCoffee
method inside the enum itself. Then you won't need a switch statement at all. You can make it an abstract method which is overridden in each enum value.
public enum CoffeeSort {
Coffee("Kaffee") {
@Override public ACoffee createCoffee() {
...
}
},
Espresso("Espresso") { ... },
Mocca("Mocca") { ... },
Cappuccino("Cappuccino") { ... },
LatteMacchiato("Latte Macchiato") { ... },
DoubleEspresso("doppelter Espresso") { ... };
private final String stringValue;
private CoffeeSorts(final String s) {
stringValue = s;
}
@Override
public String toString() {
return stringValue;
}
public abstract ACoffee createCoffee();
}
See more on this question at Stackoverflow