如何优化很多开关案例?

时间:2016-03-05 20:30:19

标签: java switch-statement

如何优化大量的开关案例?是否有其他方法可以做我想做的事情?

我有一个时间滑块,此滑块使用当前滑块所在的值(1-24)更新变量currentTime并调用updateTime()方法。在这种方法中,我的切换情况为1 - 24(本例中仅为3)。我可以用更简单的方式完成这项工作,而不是制作24个开关盒吗?

private void updateTime() {
    switch (currentTime) {
        case 1:
            hourlyData = weatherAPI.HourlyReport(1);
            setHourlyData();
            break;
        case 2:
            hourlyData = weatherAPI.HourlyReport(2);
            setHourlyData();
            break;
        ...
        case 24:
            hourlyData = weatherAPI.HourlyReport(24);
            setHourlyData();
            break;
        default:
            System.out.println("Oops");
            break;
    }
}

-

public Map HourlyReport(int hour) {
    Hourly hourly = new Hourly(fio);
    //In case there is no hourly data available
    if (hourly.hours() < 0) {
        System.out.println("No hourly data.");
    } else {
        hourlyData.put("Temp", hourly.getHour(hour).temperature()); // Temperature
        hourlyData.put("TempFeel", hourly.getHour(hour).apparentTemperature()); // Feel Temperature
        hourlyData.put("Humidity", hourly.getHour(hour).humidity()); // Humidity
        hourlyData.put("WindSpeed", hourly.getHour(hour).windSpeed()); // Wind Speed
        hourlyData.put("Precip", hourly.getHour(hour).precipProbability()); // Precipitation
        hourlyData.put("TimeStamp", hourly.getHour(hour).time());// TimeStamp
    }
    return hourlyData;
}

4 个答案:

答案 0 :(得分:6)

在这种情况下,使用开关是不合理的。使用简单的if

if (currentTime > 0 && currentTime < 25) {
    hourlyData = weatherAPI.HourlyReport(currentTime);
    setHourlyData();
} else {
    System.out.println("Oops");
}

答案 1 :(得分:2)

我先验证

private void updateTime() {
    if (currentTime < 1 || currentTime > 24) 
        throw new IllegalStateException("currentTime: " + currentTime);

    hourlyData = weatherAPI.HourlyReport(currentTime);
    setHourlyData();
}

答案 2 :(得分:1)

您可以使用简单的if语句验证currentTime的值,然后将其传递给weatherAPI.HourlyReport

private void updateTime() {
    if (currentTime >= 1 || currentTime <= 24) {
        hourlyData = weatherAPI.HourlyReport(currentTime);
        setHourlyData();
    } else{
        System.out.println("Oops");
    }
}

答案 3 :(得分:0)

    private boolean isValidHour(){
        if (currentTime >= 1 && currentTime <= 24) 
            return true;
        else
            return false;
    }


    private void updateTime() {
          if(this.isValidHour())
            hourlyData = weatherAPI.HourlyReport(currentTime);
          else
            System.out.println("Oops");
}