The code below compiles and does its job, however lets say I needed to added another 100 if
statements. Whats the most efficient way to write multiple if
statements?
public String getBattle(int num)
{
if (num == (1)){
setupBattles();
System.out.println(BattleDetails.get(0));
}else if (num == (2)){
setupBattles();
System.out.println(BattleDetails.get(1));
}else if (num == (3)){
setupBattles();
System.out.println(BattleDetails.get(2));
}else if(num == (4)){
setupBattles();
System.out.println(BattleDetails.get(3));
}else if (num == (5)){
setupBattles();
System.out.println(BattleDetails.get(4));
}else if (num == (6)){
setupBattles();
System.out.println(BattleDetails.get(5));
}else if (num == (7)){
setupBattles();
System.out.println(BattleDetails.get(6));
}else if (num == (8)){
setupBattles();
System.out.println(BattleDetails.get(7));
}else{
return "No such battle";
}
return BattleDetails.toString();
}
CodePudding user response:
Observe the pattern that every branch uses the number 1 below the number used in the condition
if (num >= 1 && num <= 8) {
setupBattles();
System.out.println(BattleDetails.get(num - 1));
}
else {
return "No such battle";
}