简体   繁体   中英

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. What is the solution for this? Here getType() method returns a 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. Else everything before the ? is considered the first part of the shorthand if-else statement.

Edit

For readeability's sake, I'd use the String.format() method:

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":

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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