关于if else多个条件

时间:2013-07-16 04:54:16

标签: java if-statement

我有一个常量文件abcder.constants,如下所示

public static final String ABC_abbject_EOD = "DDD_Report";
public static final String CDE_abbject_INTRADAY = "FFD_Report";

现在我有以下方法,如下所示

public void Gen(String[] toAddress, String[] ccAddress, String abbject,
                String message, String defIdentifier, Date date)

现在,在这种方法中,可能有两种情况,defIdentifiernullabbject参数有值

  1. 因此,如果defIdentifier为空,则abbject的值为abcderconstant,因此在这种情况下我必须做点什么。这取决于卑鄙的价值,可以是ABC_abbject_EODCDE_abbject_INTRADAY
  2. 如果defIdentifier不为null,则abbject为空,那么在这种情况下我必须执行其他操作
  3. 所以,我已经开发了如下所示的代码,请指出这是正确的方法

    if (defIdentifier != null && abbject== null)
    {
        String s = defIdentifier + "-" + formatter.format(now.getTime()) + "." + "doc";
    }
    
    if (defIdentifier == null && abbject.equalsIgnoreCase(abcderconstants.ABC_abbject_EOD))
    {
        String s = "DDD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
    }
    if (defIdentifier == null && abbject.equalsIgnoreCase(abcderconstants.CDE_abbject_INTRADAY))
    {
        String s = "FFD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
    }
    

2 个答案:

答案 0 :(得分:1)

StringBuilder sb = new StringBuilder();
if (defIdentifier != null && abbject == null) {
    sb.append(defIdentifier);
} else if (defIdentifier == null && abbject != null ) {

    if(abbject.equalsIgnoreCase(abcderconstants.ABC_abbject_EOD)) {
         sb.append("DDD-Report");
    } else if (abbject.equalsIgnoreCase(abcderconstants.CDE_abbject_INTRADAY)) {
         sb.append("FFD-Report");
    } else {
         // throw invalid abbject type exception?
    }

} else {
    // both defIdentifier and abbject are either null or not null. Illegal args?
}

sb.append("-" + formatter.format(now.getTime()) + "." + "doc");
String s = sb.toString();

答案 1 :(得分:0)

String s = ...放在if语句之外。检查abbject是否为空可能是个好主意。请尝试使用更好的变量名称。

String s = null;

if (defIdentifier != null && abbject == null) {
    s = defIdentifier + "-" + formatter.format(now.getTime()) + "." + "doc";
} 
else if (defIdentifier == null && abbject != null && abbject.equalsIgnoreCase(abcderconstants.ABC_abbject_EOD)) {
    s = "DDD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}
else if (defIdentifier == null && abbject != null && abbject.equalsIgnoreCase(abcderconstants.CDE_abbject_INTRADAY)) {
    s = "FFD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}