2015-09-29 144 views
4

我的代碼包含一個switch語句,並且在所有情況下都有if語句。它們都很短,所以我想通過將代碼變成條件語句來凝聚代碼。我要去的是格式...我可以在printf語句中使用條件語句嗎?

System.out.printf((conditional-Statement)); 

這裏是我的情況下,如果一個else語句...

if (count == 1) { 
     System.out.printf("%3d", count); 
    } else { 
     System.out.printf("%11d", count); 
    } 

喜歡的東西...

System.out.print((count == 1) ? count : " " + count); 

不會產生語法錯誤,

但這一切都搞砸了,當我做...

System.out.printf((count == 1) ? "%3d", count : "%11d", count); 

是我想要做的可能嗎?

+1

的if-else的版本看起來在這種情況下 – ZhongYu

+0

不如我完全同意@ bayou.io將該條件轉換爲三元運算符後,我覺得'if-else'更具可讀性。 –

+0

你在改變什麼?你也可以在'enum'中編寫所有代碼。 –

回答

9

是的,這是可能的。但是提醒一下,三元運算符只返回一個值,不是兩個。你所要做的必須要做這樣的:

System.out.printf((count == 1) ? "%3d" : "%11d", count); 
2

這應該是

System.out.printf((count == 1) ? "%3d": "%11d", count); 

您不必再重新添加count在條件語句表達。

要清除這裏的困惑讓我們分手。

String format = (count == 1) ? "%3d" : "%11d"; 
System.out.printf(format, count); 
2

它可以是可能的「的String.format」爲遵循

System.out.print((count==1)? String.format("%3d", count): String.format("%11d", count)); 
相關問題