簡體   English   中英

如何在Java中將條件運算符與字符串合並使用?

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

考慮一個例子:

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。

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

您錯誤地包裝了三元運算符。 將整個語句用括號括起來,而不是條件部分:

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保持字符串本身“干凈”:

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