如何组合多个if(stringname.equals(" value"))?

时间:2015-10-21 11:05:12

标签: java android string android-studio equals

我有多个字符串必须具有触发通知的特定值,但我似乎找不到合并它们的方法

String wppanswer,tbanswer,ctanswer,ssowpanswer,cppanswer;
if  (wppanswer.equals("Yes"))
            (tbanswer.equals("Yes"))
            (ctanswer.equals("Yes"))
            (ssowpanswer.equals("Yes"))
            (ssowpanswer.equals("N/A"))
            (cppanswer.equals("Yes")){

                NotificationCompat.Builder Yes =
                        new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.adccube)
                                .setContentTitle("Success!")
                                .setContentText("YEY! You have everything you need, proceed with work");
                int mNotificationId = 001;
                NotificationManager mNotifyMgr =
                        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                mNotifyMgr.notify(mNotificationId, Yes.build());
            }

提前谢谢大家,如果我需要提供更多信息,我可以做到

编辑我已经尝试过以下线程无效

Thread 1

Thread 2

Thread 3

2 个答案:

答案 0 :(得分:4)

您必须使用Java中的AND逻辑&&来使if块代码仅在所有条件都为真时执行,例如:

if (wppanswer.equals("Yes") &&
        tbanswer.equals("Yes") &&
        ctanswer.equals("Yes") &&
        ssowpanswer.equals("Yes") &&
        ssowpanswer.equals("N/A") &&
        cppanswer.equals("Yes")){
    //your code here        
}

此外,正如在评论中所说的那样,最好在代码中使用"Yes".equals(wppanswer)样式,以阻止NullPointerException wppanswer或其他任何对象当你称之为equals()方法时,它将为NULL。

答案 1 :(得分:1)

为了使代码更具可读性,请考虑重构辅助方法:

// returns true if and only if all objects are equal to each other
public static boolean allEquals(Object first, Object... rest) {
    for (Object o : rest)
        if (!Objects.equals(first, o))  // `Objects#equals` to avoid NPE 
            return false;
    return true;
}

然后在主代码中使用它:

if (allEquals("Yes", wppanswer, tbanswer, ctanswer, ssowpanswer, cppanswer) 
    && "N/A".equals(ssowpanswer)) {
    // trigger action
}