在Java中整合多个if语句

问题描述 投票:0回答:1

我有以下代码依赖于多个不同的if语句。我正在制作Android的Cribbage分数计数应用程序。显示的代码仅适用于蓝色团队,但是我最终为蓝色团队使用的代码也将用于红色和绿色团队。我现在所拥有的有效,但是体积很大。我是Java的新手,并希望获得一些有关将代码合并为更易于阅读和维护的最佳实践的指导。

    if(blueTeamScore >= ENDGAMESCORE) {
        String baseVictoryText = "Blue Team has won!";
        TextView winningTeamTextView = (TextView) findViewById(R.id.winningTeam);

        if(hasThreePlayer == false) {
            winningTeamTextView.setText(baseVictoryText);
            if (hasSkunk == true) {
                if (redTeamScore <= 90) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Red Team got Skunked");
                }
            }
        }
        if(hasThreePlayer == true) {
            winningTeamTextView.setText(baseVictoryText);
            if (hasSkunk == true) {
                if ((redTeamScore <= 90) && (greenTeamScore <= 90)) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Red and Green Teams got Skunked");
                }
                if ((redTeamScore <= 90) && (greenTeamScore >= 90)) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Red Team got Skunked");
                }
                if ((redTeamScore >= 90) && (greenTeamScore <= 90)) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Green Team got Skunked");
                }
            }
        }
    }

我知道布尔变量不能在switch语句中使用(太糟糕了,但是还有其他类似的东西可以帮助我集中代码吗?

java android if-statement switch-statement logic
1个回答
0
投票

您可以尝试使用三元运算符?:。上面代码中的示例我只是简化了一部分。您可以在其他地方尝试类似的操作

        if(!hasThreePlayer) {
            winningTeamTextView.setText(hasSkunk&&redTeamScore<=90 ? baseVictoryText + "\nAnd Red Team got Skunked" : baseVictoryText);
        }
        else {
            winningTeamTextView.setText(baseVictoryText);
            if (hasSkunk) {
                if ((redTeamScore <= 90) && (greenTeamScore <= 90)) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Red and Green Teams got Skunked");
                }
                if ((redTeamScore <= 90) && (greenTeamScore >= 90)) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Red Team got Skunked");
                }
                if ((redTeamScore >= 90) && (greenTeamScore <= 90)) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Green Team got Skunked");
                }
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.