3
\$\begingroup\$

I want to see if anyone knows how to optimize the code below:

public class smallestTest
{
   public static void main(String[] args)
   {
      double resultSmallest = smallest(2.5, 3.5, 4.5);
      System.out.println("The smallest number out of 2.5, 3.5, and 4.5 is: " + resultSmallest);
   }

  /**
  Computes the smallest of three variables
  @param x, y, z
  @returns smallestNumber
 */


    public static double smallest(double x, double y, double z)
    {
         double smallestNumber = 0;
         if ( x < y && x < z)
         {
           smallestNumber = x;

         }
         else if (y < x && y < z)
         {
            smallestNumber = y;

         }
         else if (z < x && z < y)
         {
            smallestNumber = z;

         }

         return smallestNumber;
      }
}
\$\endgroup\$
3
\$\begingroup\$

You can use something called Varargs that was introduced in java 5.

It is used in method declarations to declare arguments as an array.

public void myMethod(double... doubleArray) {
}

public void callMyMethod() {
    myMethod(1.2, 4, 2, 1); // all those are put into a double[]
}

You can adapt this to your program by doing the following:

public static double smallest(double... vals) {
    // must pass at least 1 argument. You could also return Double.NaN or something
    if(vals.length == 0) throw new IllegalArgumentException("smallest must be passed at least 1 value.");
    // start with the first value as the smallest
    double smallest = vals[0];
    for(int i=1;i<vals.length;i++) {
        // see if this ones smaller than our stored smallest
        if(vals[i] < smallest) {
            smallest = val[i];
        }
    }
    return smallest;
}

You can then call this with as many double values as you like.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.