gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:37:09 24 4
gpt4 key购买 nike

这是我的java代码

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

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

似乎这应该是一些棘手的表达。

更新

没有if/else逻辑!仅使用 format 内的表达式方法。

最佳答案

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

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

也可以。

关于java - 当选项为空时,如何从格式表达式中排除参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27581055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com