【问题标题】:How do I make this code shorter [closed]如何使这段代码更短[关闭]
【发布时间】:2017-08-04 22:52:20
【问题描述】:

如何使这段代码更短我已经尝试了所有方法!

if(((condition.toString()).length()) == ("false".length()) - 1&&((condition.toString()).length()) != "true".length() + 1){
            System.out.println("true");
        }

【问题讨论】:

  • condition 是什么,具体来说,您想做什么?
  • 你可以去掉一些多余的括号。
  • 拉出condition.toString().length()作为变量:int c = condition.toString().length();。然后内联字符串的长度:if (c == 4 && c != 5) { ... }。所以,简单地说:if (c == 4).
  • 对不起,伙计们,我认为这是精心策划的拖钓,而不是真正的问题。代码只是if(condition) 的一种复杂方式 - 任何人几乎不可能意外到达此版本。
  • 我猜这是 Aaron 的测试题。

标签: java


【解决方案1】:

假设condition.toString().length() 在两次评估时都相同,将其作为变量拉出:

int c = condition.toString().length();

然后内联("false".length()) - 1"true".length() + 1的值:

if (c == 4 && c != 5) { ... }

由于 4 != 5:

if (c == 4) {
  System.out.println("true");
}

如果您不想使用 c 变量:

if (condition.toString().length() == 4) {
  System.out.println("true");
}

如果您无法假设condition.toString().length() 两次都相同,那么您所能做的就是删除不必要的括号并将("false".length()) - 1"true".length() + 1 的值内联。

if (condition.toString().length() == 4
    && condition.toString().length() != 5) {
  System.out.println("true");
}

【讨论】:

    【解决方案2】:

    看来你的支票可以简化成这样。

    int c = condition.toString().length();
    
        if(c == 4){
         ...
    }
    

    第二次检查是否 c!= 5 是不必要的,因为如果 c == 4 它永远不会等于 5!

    【讨论】:

      【解决方案3】:

      您可以删除不必要的分组符号,并为 你用得最多的condition.toString().length()

      int condL = condition.toString().length();
      if (condL == "false".length() - 1 && condL != "true".length() + 1) {
          System.out.println("true");
      }
      

      【讨论】:

        【解决方案4】:

        好吧,我尝试自己迭代代码以将其简化为 -

        if(((condition.toString()).length()) == ("false".length()) - 1&&((condition.toString()).length()) != "true".length() + 1) {
            System.out.println("true");
        }
        

        去掉括号 -

        if ( condition.toString().length() == ("false".length()) - 1 && (condition.toString()).length() != "true".length() + 1) {
                System.out.println("true");
        }
        

        替换常量值 -

        if ( condition.toString().length() == 4 && (condition.toString()).length() != 5) {
            System.out.println("true");
        }
        

        作为Suggested by @Andy

        int c = condition.toString().length();
        if (c == 4) {
            System.out.println("true");
        }
        

        进一步简化(注意这个处理else 部分条件以及我打印新行""

        int c = condition.toString().length();
        System.out.println(c==4?"true":"");
        

        一个班轮-

        System.out.println(condition.toString().length()==4?"true":"");
        

        【讨论】:

        • “进一步简化”不,这不是一回事。
        • @AndyTurner - 是的,我应该提到其他部分(Y)什么都不做。我希望这也是你所指的。
        • 请拒绝投票的原因。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-11
        • 2020-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多