听起来你最好使用带有枚举类型的 switch 块。
您将创建一个像这样的枚举:
public enum Units {
METERS_TO_FEET("meters", "feet"), FEET_TO_METERS("feet", "meters") /**, etc...*/;
private final String from;
private final String to;
public Units(final String from, final String to) {
this.from = from;
this.to = to;
}
public static Units fromStrings(String from, String to) {
if (from != null && to !=null) {
for (Unit u : Unit.values()) {
if (from.equalsIgnoreCase(u.from) && to.equalsIgnoreCase(u.to)) {
return u;
}
}
}
return null;
}
}
并在您的转换方法中使用 switch 块:`
public int convert(String convertFrom, String convertTo, float fromVal, float toVal) {
Units u = Units.fromStrings(convertFrom, convertTo);
if(u == null) {
throw new IllegalArgumentException("Bad input");
}
switch(u) {
case METERS_TO_FEET :
/** return meters to feet method on fromVal, toVal */
break;
case FEET_TO_METERS :
/** return feet to meters method on fromVal, toVal */
break;
/** etc. */
}
}