有没有一种更短的方式编写此代码,而无需重复三遍切换?

时间:2018-08-24 06:44:21

标签: java switch-statement

是否有更好(更短)的代码编写方式?谢谢

public double getPrice(int day, String currency) throws SecurityException{      
    if(currency.toLowerCase().equals(PriceItem.GBP)){
        switch(day){
            case 1: return getDay1Gbp();
            case 2: return getDay2Gbp();
            case 3: return getDay3Gbp();
            case 4: return getDay4Gbp();
            case 5: return getDay5Gbp();
            case 6: return getDay6Gbp();
            case 7: return getDay7Gbp();
            case 8: return getDay8Gbp();
            case 9: return getDay9Gbp();
            case 10: return getDay10Gbp();
            case 11: return getDay11Gbp();
            case 12: return getDay12Gbp();
            case 13: return getDay13Gbp();
            case 14: return getDay14Gbp();
            default: return 0.;
        }
    } else if(currency.toLowerCase().equals(PriceItem.EUR)){
        switch(day){
            case 1: return getDay1Eur();
            case 2: return getDay2Eur();
            case 3: return getDay3Eur();
            case 4: return getDay4Eur();
            case 5: return getDay5Eur();
            case 6: return getDay6Eur();
            case 7: return getDay7Eur();
            case 8: return getDay8Eur();
            case 9: return getDay9Eur();
            case 10: return getDay10Eur();
            case 11: return getDay11Eur();
            case 12: return getDay12Eur();
            case 13: return getDay13Eur();
            case 14: return getDay14Eur();
            default: return 0.;
        }
    } else if(currency.toLowerCase().equals(PriceItem.USD)){
        switch(day){
            case 1: return getDay1Usd();
            case 2: return getDay2Usd();
            case 3: return getDay3Usd();
            case 4: return getDay4Usd();
            case 5: return getDay5Usd();
            case 6: return getDay6Usd();
            case 7: return getDay7Usd();
            case 8: return getDay8Usd();
            case 9: return getDay9Usd();
            case 10: return getDay10Usd();
            case 11: return getDay11Usd();
            case 12: return getDay12Usd();
            case 13: return getDay13Usd();
            case 14: return getDay14Usd();
            default: return 0.;
        }
    }
    return 0.;
}

我正在尝试编写此代码,而无需重复三遍切换,但是我不知道如何写得更短。如果我连接参数,也许返回方法。我不知道这个想法是否可能。谢谢你的建议

1 个答案:

答案 0 :(得分:1)

我找到了问题的答案。

Field field = this.getClass().getDeclaredField(nameOfField);
return (Double) field.get(this);