有几种方法可以做到这一点。
一种简单的方法是将奖励分配给变量。在该循环结束时,reward
以下变量将是适用的最高击杀奖励
public static void main (String[] args) {
KillReward reward = null;
for (KillReward k : KillReward.values()) {
if (playerKills > k.getKillsNeeded()) {
reward = k;
}
}
System.out.println("Kills: " + playerKills + "; Reward: " + k.getKillReward());
}
请注意,这依赖于按顺序列出的枚举,有时可能很脆弱。例如,如果在 CHAMPION 之后添加了一个新的 KillReward 枚举,但它的 killsNeeded 值较低,则它不会返回正确的值。
更好的解决方案是创建一个 Comparator 并使用它首先按 killsNeeded 对枚举值进行排序,从而确保它们始终有序。如果您还按降序对其进行排序,那么您也可以在您点击第一个适用的循环后中断循环。
class EnumTest {
private enum KillReward {
BEGINNER(10, 150), JUNIOR(25, 300), EXPERT(50, 500), CHAMPION(100, 1000);
// Sort KillRewards once at initialization
private static final List<KillReward> sortedKillRewards = new ArrayList<KillReward>();
static {
for (KillReward k : values())
sortedKillRewards.add(k);
Collections.sort(sortedKillRewards, new Comparator<KillReward>() {
@Override
public int compare(KillReward o1, KillReward o2) {
return (o1.kills - o2.kills) * -1; // multiplying by -1 makes it
// descending
}
});
}
private KillReward(int kills, int reward) {
this.kills = kills;
this.reward = reward;
}
private int kills, reward;
private int getKillsNeeded() {
return kills;
}
private int getKillReward() {
return reward;
}
public static KillReward forKills(int killCount) {
for (KillReward k : sortedKillRewards)
if (killCount >= k.kills)
return k;
// must not have enough kills for any reward
return null;
}
}
public static void main(String[] args) {
int kills = 9;
System.out.println("Kills: " + kills + "; Reward: "
+ KillReward.forKills(kills));
kills = 10;
System.out.println("Kills: " + kills + "; Reward: "
+ KillReward.forKills(kills));
kills = 38;
System.out.println("Kills: " + kills + "; Reward: "
+ KillReward.forKills(kills));
}
}