vendredi 7 octobre 2016

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.

Aucun commentaire:

Enregistrer un commentaire