替代编码而不是" if else" Android的逻辑

时间:2017-02-18 00:15:14

标签: android

我创建了一个脚本,根据所选的选项显示结果。

我需要:A,B,C,D(0,1,-1)

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

Ansver将是16种组合中的一种。

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

我想展示潜在的变种 按下组合时:A1, B1 = "Nr1,Nr2,Nr3,Nr4"
按下组合时:A1, D1 = "Nr1,Nr3,Nr5,Nr7"
稍后会有更多变量EFGH ....等等。但答案只会是第16个
可能是什么逻辑,我有点卡住了?
If / Else似乎太长了。

示例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
    }

2 个答案:

答案 0 :(得分:2)

想到的一些替代方案:

  1. 一长串if...else陈述。

  2. switch陈述。不过,这比if...else要好得多。

  3. 数据结构,例如Map

  4. 自定义类层次结构。通常,switch语句可以被多态性替换。这在很大程度上取决于你真正做的具体细节。

答案 1 :(得分:1)