Return the minimum and maximum of all numbers in the variable argument nums as an array. - Java Object Oriented Design

Java examples for Object Oriented Design:Method Parameter

Description

Return the minimum and maximum of all numbers in the variable argument nums as an array.

Demo Code


public class Main {

  /**/* w  w w  .  j a v a2  s  .co m*/
   * Return the minimum and maximum of all numbers in the variable argument nums
   * as an array. Please see java.lang.Number for understanding properties of
   * Number. Your program should pass the following tests:
   * <ul>
   * <li>minMax() return {}
   * <li>minMax(3) return {3D,3D}.
   * <li>minMax(10, 20D, 3) return {3D, 20D}
   * <li>mainMax(new BigInteger("200"), 20D, -3L) return {-3D, 200D}.
   * </ul>
   *
   * @param nums
   *          a array of Numbers.
   * @return a double array with minimum value put at position 0 and maximum value
   *         put at position 1 or an empty array if there is no input.
   */
  @SafeVarargs
  public static <N extends Number> double[] minMax(N... nums) {
    // replace following code by yours.
    double[] ans;

    if (nums.length == 0) {
      ans = new double[0];
    } else {
      ans = new double[2];

      ans[0] = ans[1] = nums[0].doubleValue();

      for (Number t : nums) {
        if (t.doubleValue() <= ans[0])
          ans[0] = t.doubleValue();
        if (t.doubleValue() >= ans[1])
          ans[1] = t.doubleValue();
      }

    }
    return ans;

  }
}

Related Tutorials