2013-02-06 29 views
0

好吧,我需要解决这个问题,使用最小的if else条件。让我解释我的问题。 假设有三个字符串城市,州和国家,我需要的,如果城市=“”,那么它需要解决使用最小如果其他

state,country 

如果打印出来的格式如下

city,state,country 

在情况下,如果状态= “” 的它需要

city,country 

如果国家= “” 然后

city,state 

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

+0

如果所有的人都是'“”'? – nneonneo

+1

你尝试了什么?您何时想显示逗号[s]? –

+0

只需打印“”。 – ntstha

回答

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); 
+0

你打败了我!这是最好的解决方案。 – nneonneo

+0

似乎没有工作,如果国家和国家是空的,但你有城市only.Print城市,, – ntstha

+0

哦。我的错。固定。 –

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.我会使用番石榴的Joiner这样的任务。

+3

逗号在哪里? – Dukeling

+0

@Dukeling最初错过了。 –

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); 
+4

认为你需要''(“城市”+“,”)'等 –

+2

如果'country'为空?你会打印'城市,州,'(最后不需要的逗号)。 – Dukeling

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); 
+0

最后总会有一个额外的逗号。 – jlordo

+0

谢谢,修复。 – CloudyMarble

+0

现在它会崩溃,如果所有三个字符串都是空的 – jlordo