2015-09-29 146 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)); 
相关问题