减少if语句的数量,或替换为for或switch或其他

我的条件ifelse if条件太长了。是否可以放置一个forwhileswitch或任何其他可以减少代码并使其更易于理解的函数?

除此之外,代码运行良好。

if((text.charAt(7)=='O' || text.charAt(7)=='X')
        && (text.charAt(8)=='O' || text.charAt(8)=='X')
        && (text.charAt(9)=='O' || text.charAt(9)=='X') 
        && (text.charAt(10)=='O'|| text.charAt(10)=='X')
        && text.charAt(49)=='O'
        && text.charAt(50)=='O'
        && text.charAt(51)=='X')
 {
    ledGeneral.setBackgroundResource(R.drawable.ledverte);
}else if (text.charAt(7)=='A' 
        || text.charAt(8)=='A'
        || text.charAt(9)=='A'
        || text.charAt(10)=='A'
        || text.charAt(49)=='A'
        || text.charAt(50)=='A')
{
    ledGeneral.setBackgroundResource(R.drawable.ledgeneralrouge);
}else{
    ledGeneral.setBackgroundResource(R.drawable.imageverte);
}

回答

您可以创建一个辅助函数来处理:

static boolean check_letter(String text, char to_check, int ...pos){
    for (int po : pos) {
        if (text.charAt(po) == to_check)
            return true;
    }
    return false;
}

然后调整 if 和 else:

if((check_letter(text, 'O', 7, 8, 9, 10) || check_letter(text, 'X', 7, 8, 9, 10)) && text.charAt(49) == 'O' && text.charAt(50) == 'O' && text.charAt(51) == 'X')
{
  ...
}
else if (check_letter(text, 'A', 7, 8, 9, 10, 49, 50))
{
 ...
}


以上是减少if语句的数量,或替换为for或switch或其他的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>