当选项为空时,如何从格式表达式中排除参数?

问题描述 投票:0回答:2

这是我的java代码

System.out.format("a: %s b: %s c: %s", s1, s2, s3);

如果

s2
为空,我想打印
a: <val> c: <val>
而不带
b: null
。如果
s3
或任何其他参数为空,我也想跳过它。

看起来这应该是一些棘手的表达方式。

更新

没有

if/else
逻辑!仅在
format
方法内部使用表达式。

java formatter
2个回答
1
投票

将其分成三个调用似乎更容易

System.out.format("a: %s", s1);
if (s != null)
    System.out.format(" b: %s", s2);
System.out.format(" c: %s", s3);

如果您绝对想将其放入单个调用中,例如

System.out.format("a: %s%s%s c: %s", s1,
    (s2==null)?"":" b: ",
    (s2==null)?"":s2,
    s3);

也可以工作。


1
投票

如果你坚持要一句台词,这里是一种可能性:

    System.out.format(
            (( s1 == null ? "" : "a: %1$s" )
            + ( s2 == null ? "" : " b: %2$s" )
            + ( s3 == null ? "" : " c: %3$s" )).trim(),
            s1, s2, s3
    );

(是的,严格来说不是一句台词,而是一个声明)。

想法:根据给定字符串是否为空来构建格式字符串。

trim()
用于消除
b:
c:
之前的初始空间,以防
s1
为空。

© www.soinside.com 2019 - 2024. All rights reserved.