Bluasul Bluasul - 1 month ago 7
Java Question

Making if-else solution more efficient, less lines of code (Java)

Is there a more efficient way to code something like this without using as many if-else statements?

private int group1, group2, group3, group4;
private int total = 0

public void assignMembers()
{
group1 = (int)((6 * Math.random()) + 1);
group2 = (int)((6 * Math.random()) + 1);
group3 = (int)((6 * Math.random()) + 1);
group4 = (int)((6 * Math.random()) + 1);
}

public void calculateSomething()
{
if(group1 == 3)
{
total += 2;
}
else if(group1 == 5)
{
total += 4;
}

if(group2 == 3)
{
total += 2;
}
else if(group2 == 5)
{
total += 4;
}

if(group3 == 3)
{
total += 2;
}
else if(group3 == 5)
{
total += 4;
}

if(group4 == 3)
{
total += 2;
}
else if(group4 == 5)
{
total += 4;
}
{


The if-else statements are adding two to the total if the group has 3 member and 4 if the group has 5 members.

I know I can maybe do something more efficient with a "groups" array, but is there a way without an array? Maybe a way for the calculateSomething method to get the number of team member of each group without having to repeat if-else so much? Any suggestions would be appreciated.

Answer

If you seem find a redundant pattern in your code that's the time you are going to create a re-usable function.

private int group1, group2, group3, group4;
private int total = 0;

    public void assignMembers()
    {
        group1 = (int)(Math.random()*6 + 1);
        group2 = (int)(Math.random()*6 + 1);
        group3 = (int)(Math.random()*6 + 1);
        group4 = (int)(Math.random()*6 + 1);

        calc(group1);
        calc(group2);
        calc(group3);
        calc(group4);
    }

    public void calc(int group)
    {
        switch (group){
                case 3:
                  total += 2;
                  break;
                case 5:
                  total += 4;
                  break;
        }
    }

Update answer - since the requirements is : The method must be called outside the class.

private int group1, group2, group3, group4;
    private int total = 0;

        public void assignMembers()
        {
            group1 = (int)(Math.random()*6 + 1);
            group2 = (int)(Math.random()*6 + 1);
            group3 = (int)(Math.random()*6 + 1);
            group4 = (int)(Math.random()*6 + 1);
        }

        private void calc(int group)
        {
            switch (group){
                    case 3:
                      total += 2;
                      break;
                    case 5:
                      total += 4;
                      break;
            }
        }

        public void calculateSomething(){
            calc(group1);
            calc(group2);
            calc(group3);
            calc(group4);
        }
Comments