Mārtiņš Doniņš
Mārtiņš Doniņš

Reputation: 11

Alternative codeing instead of "if else" logic for Android

I create a script that displays the results depending on the selected options.

I need: A, B, C, D (0,1,-1)

int A = 0;
int B = 0;
int C = 0;
int D = 0;

Ansver will be one of 16 combination.

if A = 1 = A1;
if A = -1 = A2;
if B = 1 = B1;
if B = -1 B2;
if C = 1 = C1;
If C = -1 = C2;
If D = 1 = D1;
if D = -1 = D1;

A1;B1;C1;D1 = Nr1
A1;B1;C1;D2 = Nr2
A1;B1;C2;D1 = Nr3
A1;B1;C2;D2 = Nr4
A1;B2;C1;D1 = Nr5
A1;B2;C1;D2 = Nr6
A1;B2;C2;D1 = Nr7
A1;B2;C2;D2 = Nr8
A2;B1;C1;D1 = Nr9
A2;B1;C1;D2 = Nr10
A2;B1;C2;D1 = Nr11
A2;B1;C2;D2 = Nr12
A2;B2;C1;D1 = Nr13
A2;B2;C1;D2 = Nr14
A2;B2;C2;D1 = Nr15
A2;B2;C2;D2 = Nr16

I want to show the potential variants.
When you press the combination of: A1, B1 = "Nr1,Nr2,Nr3,Nr4"
When you press the combination of: A1, D1 = "Nr1,Nr3,Nr5,Nr7"
Later will be more variables E, F, G, H .... etc. But the answers will only 16th

What could be the logic, I'm a little stuck?
If / Else seems to be too long.

Example if/else:

    if (A == 1) {
        if (B == 1) {
            if (C == 1) {
                if (D == 1) {
                    scoreTeamA = "Nr1"; //A1,B1,C1,D1
                } else if (D == -1) {
                    scoreTeamA = "Nr2"; //A1,B1,C1,D2
                } else scoreTeamA = "Nr1, Nr2"; //A1,B1,C1
            } else if (B == 1) {
                if (D == 1) {
                    scoreTeamA = "Nr3"; //A1,B1,C1,D1
                } else if (D == -1) {
                    scoreTeamA = "Nr4"; //A1,B1,C1,D2
                } else scoreTeamA = "Nr3,Nr4"; //A1,B1,C2
            } else scoreTeamA = "Nr1,Nr2,Nr3,Nr4"; //A1,B1
        } else if (B == -1) {
            scoreTeamA = "Nr5,Nr6,Nr7,Nr8";//A1,B2
        } else
            scoreTeamA = "Nr1,Nr2,Nr3,Nr4,Nr5,Nr6,Nr7,Nr8"; //A1
    } else if (A == -1) { 
        scoreTeamA = "Nr9,Nr10,Nr11,Nr12,Nr13,Nr14,Nr15,Nr16"; //A2
    }

Upvotes: 0

Views: 331

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83577

Some of the alternatives that come to mind:

  1. A long chain of if...else statements.

  2. switch statements. This won't be much better than if...else, though.

  3. A data structure, such as a Map.

  4. A custom class hierarchy. Often a switch statement can be replaced by polymorphism. This is highly dependent on the specifics of what you are really doing.

Upvotes: 2

Patricia
Patricia

Reputation: 2865

For that you are using switch-case. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Upvotes: 1

Related Questions