gpt4 book ai didi

java - 字符串值未显示两个变量值

转载 作者:行者123 更新时间:2023-12-04 16:37:24 26 4
gpt4 key购买 nike

我想将字符串值设置为 fileName + ".yaml"+ comment != null ? comment : ""+ date.toString()其中 fileName 和 comment 是 String 类型,但表达式不显示 filenema.yaml 和日期,而只显示不为空的注释。我的表达有什么问题?

最佳答案

我强烈怀疑这个问题是优先级的。我希望它被视为:

String value = (fileName + ".yaml" + comment) != null ? comment : "" + date.toString();

第一个表达式永远不会为空,所以它总是取条件运算符的第二个操作数而不是第三个。即使那样,我认为代码在优先级方面还不清楚......我肯定会更明确。

我怀疑您实际上希望它解析为:

String value = fileName + ".yaml" + (comment != null ? comment : "") + date.toString();

...所以明确一点。请注意,您不需要 toString() 调用 - 这是隐含的,因为您使用的是字符串连接。所以你可以有:

String value = fileName + ".yaml" + (comment != null ? comment : "") + date;

(我怀疑有更简单的方法可以用字符串格式表达这一点,但它至少应该做你想做的。)

另一种选择是将条件运算符移到单独的语句中:

String commentOrEmpty = comment == null ? "" : comment;
String value = fileName + ".yaml" + commentOrEmpty + date;

关于java - 字符串值未显示两个变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68223038/

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