如何在java中使用带字符串连接的条件运算符?

时间:2014-12-22 12:52:26

标签: java 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() + " ]");

当我这样做时,我得到无法从String转换为布尔错误。这是什么解决方案? 这里getType()方法返回一个String。

2 个答案:

答案 0 :(得分:0)

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()) + " ]");

或者,简而言之:在括号中加上你的简写if-else语句。此外,?之前的所有内容都被视为简写if-else语句的第一部分。

修改

出于可重复性的考虑,我使用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()));

答案 1 :(得分:0)

您错误地包裹了您的三元运算符。将整个语句包含在括号中,而不仅仅是 condition 部分:

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()) + " ]");

您还可以使用String.format来保持字符串本身&#34;清理&#34;:

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