Search code examples
javaif-statementcomposite

Is there a way to group if statements in Java


I am writing a function to produce an array however I have to apply lots of if statements that will affect the output.

I have tried just listing them but I think it is affecting my output somehow, it also looks very cumbersome.

static double [] solve (equation b, int k)
{
  double [] a = null;
  if (b.c > 1)
  {   
    a = new double[k];
    for (int i = 0; i < k; i++)
    {
      b.x0 = (b.c*b.x0)/(b.y0) + (b.d*b.x0);
      b.y0 = b.e*(b.x0 + 1)*b.y0;
      a[i] = b.y0;
    }
  } 
  if (b.d > 0)
  {   
    a = new double[k];
    for (int i = 0; i < k; i++)
    {
      b.x0 = (b.c*b.x0)/(b.y0) + (b.d*b.x0);
      b.y0 = b.e*(b.x0 + 1)*b.y0;
      a[i] = b.y0;
    }
  }
  if (1 > b.e || b.e > 0)
  {   
    a = new double[k];
    for (int i = 0; i < k; i++)
    {
      b.x0 = (b.c*b.x0)/(b.y0) + (b.d*b.x0);
      b.y0 = b.e*(b.x0 + 1)*b.y0;
      a[i] = b.y0;
    }
    return a;

Is there a way to group my if statements so that if my parameters are within the required range I will get a result and if they are not I will get 'null'. (there are also a few more if statements but this gets the idea across).


Solution

  • All of your loop(s) do the same thing, so a single if with all of the conditions in an or should do it. Like,

    static double[] solve(equation b, int k) {
        if (b.c > 1 || b.d > 0 || 1 > b.e || b.e > 0) {
            double[] a = new double[k];
            for (int i = 0; i < k; i++) {
                b.x0 = (b.c * b.x0) / (b.y0) + (b.d * b.x0);
                b.y0 = b.e * (b.x0 + 1) * b.y0;
                a[i] = b.y0;
            }
            return a;
        }
        return null;
    }