简体   繁体   English

如何在Java中将条件运算符与字符串合并使用?

[英]How to use conditional operator with string concatination in java?

Consider an example: 考虑一个例子:

if (sourceRule.getMaxOutput() <= 0 || targetRule.getMaxInput() <= 0)
    throw new Exception("Connection [ " + connectionType + " ] not possible between components [ "
        + (source instanceof Component) ? sourceCom.getType() : sourceMap.getType() + " ] and [ "
        + (target instanceof Component) ? targetCom.getType() : targetMap.getType() + " ]");

When I do this, I get cannot convert from String to boolean error. 当我这样做时,我无法从String转换为布尔错误。 What is the solution for this? 有什么解决方案? Here getType() method returns a String. 这里的getType()方法返回一个String。

if (sourceRule.getMaxOutput() <= 0 || targetRule.getMaxInput() <= 0)
    throw new Exception("Connection [ " + connectionType + " ] not possible between components [ "
        + (source instanceof Component ? sourceCom.getType() : sourceMap.getType()) + " ] and [ "
        + (target instanceof Component ? targetCom.getType() : targetMap.getType()) + " ]");

Or, in short: put your shorthand if-else statement between brackets. 或者,简而言之:将简写的if-else语句放在方括号之间。 Else everything before the ? 其他一切之前? is considered the first part of the shorthand if-else statement. 被视为简写if-else语句的第一部分。

Edit 编辑

For readeability's sake, I'd use the String.format() method: 出于可读性考虑,我将使用String.format()方法:

if (sourceRule.getMaxOutput() <= 0 || targetRule.getMaxInput() <= 0)
    throw new Exception(String.format("Connection [ %s ] not possible between components [ %s ] and [ %s ]", 
            connectionType,
            source instanceof Component? sourceCom.getType() : sourceMap.getType(),
            target instanceof Component? targetCom.getType() : targetMap.getType()));

You've wrapped your ternary operators incorrectly. 您错误地包装了三元运算符。 Wrap the whole statement in parenthese, instead just the condition part: 将整个语句用括号括起来,而不是条件部分:

if (sourceRule.getMaxOutput() <= 0 || targetRule.getMaxInput() <= 0)
    throw new Exception("Connection [ " + connectionType + " ] not possible between components [ "
        + (source instanceof Component? sourceCom.getType() : sourceMap.getType()) + " ] and [ "
        + (target instanceof Component? targetCom.getType() : targetMap.getType()) + " ]");

You could also use String.format to keep the String itself "clean": 您还可以使用String.format保持字符串本身“干净”:

if (sourceRule.getMaxOutput() <= 0 || targetRule.getMaxInput() <= 0)
  throw new Exception(String.format("Connection [ %s ] not possible between components [ %s ] and [ %s ]",
      connectionType,
      source instanceof Component ? sourceCom.getType() : sourceMap.getType(),
      target instanceof Component ? targetCom.getType() : targetMap.getType()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM