解决使用最小if else

时间:2013-02-06 07:17:04

标签: java logic

好的伙计们,我需要使用最小的if else条件解决这个问题。让我解释一下我的问题。 假设有三个String city,state和country.I需要以下列格式打印

city,state,country

如果city =“”则需要

state,country

如果state =“”,则需要

 city,country

如果country =“”那么

city,state

如果所有字符串都是“”,则不应打印任何内容或仅打印“”。 和其他所有可能的条件。这三个字符串可能有价值或可能包含“”非null。所以使用最少if else条件我需要解决这个问题。 注意:不是作业。

4 个答案:

答案 0 :(得分:10)

StringBuilder sb = new StringBuilder ();
for (String s: new String [] {city, state, country})
{
    if (!s.isEmpty ())
    {
        if (sb.length () > 0) sb.append (",");
        sb.append (s);
    }
}
System.out.println (sb);

答案 1 :(得分:2)

您可以通过以下方式执行此操作:

StringBuilder builder = new StringBuilder();
builder.append((city.isEmpty() ? "" : city + ","))
       .append(((state.isEmpty() ? "" : state + ",")))
       .append(((country.isEmpty() ? "" : country)));
String result = builder.toString();
if (result.endsWith(","))
    result = result.substring(0, result.length() - 1);
System.out.println(result);

虽然不是很优雅。

P.S。我会用guava的Joiner来完成这项任务。

答案 2 :(得分:1)

将它们全部添加到数组或列表中,然后使用字符串构建器构建输出,如下所示(伪代码):

StringBuilder sb = new StringBuilder();
for(int i=0; i<array.length-1; i++)
   if (!"".equals(array[i]))
      stringbuilder.append(s + ",");                   

if (sb.length() > 0)
  sb.deleteCharAt(sb.length()-1); 

答案 3 :(得分:0)

String finalString =(city.equals("") ? "" : ("city"  + ",")) +
                    (state.equals("")? "" : ("state" + ",")) +
                    country.equals("") ? "" : "country"

finalString = finalString.endsWith(",") ? finalString.substring(0, finalString.length-1) : finalString;

System.out.println(finalString);