Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple if Statements in a Efficient Way JAVA

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();
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading