有没有一种方法可以简化Java中的if..else语句

时间:2020-08-07 11:28:26

标签: java android-studio if-statement switch-statement

我有这个if语句,用于检查一项运动的ID并根据该运动设置图像。 但我很好奇是否有更简单,更短的方法来实现这一目标。 谢谢您的时间和回答!

if (sport.equals("1")) {
    sportImg.setImageResource(R.drawable.fudbal);
} else if (sport.equals("2")) {
    sportImg.setImageResource(R.drawable.hokej);
} else if (sport.equals("3")) {
    sportImg.setImageResource(R.drawable.basketball);
} else if (sport.equals("4")) {
    sportImg.setImageResource(R.drawable.tenis);
} else if (sport.equals("5")) {
    // sportImg.setImageResource(R.drawable.handball);
} else if (sport.equals("6")) {
    // sportImg.setImageResource(R.drawable.mlb);
} else if (sport.equals("7")) {
    sportImg.setImageResource(R.drawable.odbojka);
} else if (sport.equals("8")) {
    sportImg.setImageResource(R.drawable.ragbi);
} else if (sport.equals("9")) {
    // sportImg.setImageResource(R.drawable.formula);
} else if (sport.equals("10")) {
    // sportImg.setImageResource(R.drawable.moto);
} else if (sport.equals("11")) {
    sportImg.setImageResource(R.drawable.vaterpolo);
} else if (sport.equals("12")) {
    // sportImg.setImageResource(R.drawable.boks);
} else if (sport.equals("13")) {
    sportImg.setImageResource(R.drawable.futsal);
} else if (sport.equals("14")) {
    // sportImg.setImageResource(R.drawable.tenis);
} else {
    sportImg.setImageAlpha(0);
}

1 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用Map<String, Integer>来简化if..else语句:

Map<String, Integer> mapImages = new HashMap<>();

mapImages.put("1", R.drawable.fudbal);
mapImages.put("2", R.drawable.hokej);
// mapImages.put(...

Integer imageId = mapImages.get(sport);
if (imageId != null) {
    sportImg.setImageResource(imageId);
} else {
    sportImg.setImageAlpha(0);
}

或者您可以使用Map<String, Runnable>为每个key做一些事情:

Map<String, Runnable> mapActions = new HashMap<>();

mapActions.put("1", () -> System.out.println("Action 1"));
mapActions.put("2", () -> System.out.println("Action 2"));

Runnable defaultAction = () -> System.out.println("Default action");

mapActions.getOrDefault("1", defaultAction).run(); // Action 1
mapActions.getOrDefault("2", defaultAction).run(); // Action 2
mapActions.getOrDefault("3", defaultAction).run(); // Default action

或者您可以使用普通的Java strings in switch statements

String typeOfDay;
switch (dayOfWeekArg) {
    case "Monday":
        typeOfDay = "Start of work week";
        break;
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
        typeOfDay = "Midweek";
        break;
    case "Friday":
        typeOfDay = "End of work week";
        break;
    case "Saturday":
    case "Sunday":
        typeOfDay = "Weekend";
        break;
    default:
        throw new Exception("Invalid day of the week: " + dayOfWeekArg);
}