我的代码包含一个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);
是我想要做的可能吗?
的if-else的版本看起来在这种情况下 – ZhongYu
不如我完全同意@ bayou.io将该条件转换为三元运算符后,我觉得'if-else'更具可读性。 –
你在改变什么?你也可以在'enum'中编写所有代码。 –