【问题标题】:More elegant way of guarantying a method can´t use negative numbers?保证方法的更优雅的方式不能使用负数?
【发布时间】:2014-07-22 20:51:01
【问题描述】:

我必须为我的班级做这个练习。我无法改变该方法的工作方式,这是一种非常愚蠢的方法。不过,我想知道是否有更优雅的方式来保证这种方法不能使用负数。我用了一个相当大的 if:

void abreTeatro(int codigoCamarote,  int capacidadeCamarote, 
        int precoCamarote, int codigoFrente, int capacidadeFrente, 
        int precoFrente, int codigoMeio, int capacidadeMeio, 
        int precoMeio, int codigoFundo, int capacidadeFundo, 
        int precoFundo)
{
    if ((codigoCamarote > 0) && (capacidadeCamarote > 0)
            && (precoCamarote > 0) && (codigoFrente > 0)
            && (capacidadeFrente > 0) && (precoFrente > 0)
            && (codigoMeio > 0) && (capacidadeMeio > 0) 
            && (precoMeio >0) && (codigoFundo > 0) 
            && (capacidadeFundo > 0) && (precoFundo > 0))
    {
        //do Something};
    }
}

这是一个丑陋的代码.... 即使我仍然使用代码的 IF 部分,是否可以使用替代语法来使此代码更美观?

【问题讨论】:

  • 是否可以将这些值合并到一个对象中并在构建时执行验证?

标签: java if-statement negative-number


【解决方案1】:

听起来你应该在这里有对象——一个camarote对象、一个frente对象、一个meio对象、一个fundo对象——每个对象都有三个字段,这些字段由构造函数为非负数。

【讨论】:

  • (如果你检查的是>= 0,而不是> 0,你可以使用像(a | b | c | d | e | ...) >= 0这样的位旋转技巧,相当于a >= 0 && b >= 0 && c >= 0 && ...
【解决方案2】:

如果你不能使用 Louis 建议的构造方法,那么试试这个

void abreTeatro(int... values) {
   for(int val: values) {
      if(val <=0) {
         // print error if needed
         return;
      }
    }
    // Code here assuming everything is +ve
    // you have an array in values, so you have to retrieve the values in the same order as in the calling method

 }

【讨论】:

    【解决方案3】:

    你可以使用辅助方法:

    public static boolean allPositive(int... numbers)
    {
      for(int number : numbers)
      {
        if(number < 0)
          return false;
      }
    
      return true;
    }
    

    然后使用例如

    if (allPositive(codigoCamarote,capacidadeCamarote,precoCamarote,codigoFrente,capacidadeFrente,precoFrente,codigoMeio,capacidadeMeio,precoMeio,codigoFundo,capacidadeFundo,precoFundo)
    {
      //do Something
    };
    

    或者,要消除大括号使用:

    if(!allPositive(...))
      return;
    
    // do something
    

    【讨论】:

      猜你喜欢
      • 2011-10-03
      • 1970-01-01
      • 2013-11-14
      • 2015-10-10
      • 2011-08-02
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多