0

When I run this program, it finds the max number but always prints 0.0 as the minimum.

When I use Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY instead of setting smallest and largest to x[0], it works correctly.

Using Math.min and Math.max also gives me the same error but works with Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY as well. I looked at several other similar questions and I'm not allowed to use Array.sort or any of the other suggestions people post.

I just want to know why setting both variables to x[0] only ever works to find the largest number, whether I declare that variable first, second or set it equal (Double largest, smallest = x[0]).

public class MaxAndMin {
    public static void main (String[] args) {
        Scanner s= new Scanner(System.in);
        System.out.println("How many numbers would you like to enter?");
        int n= s.nextInt();

        double[] x= new double[n];
        double smallest= x[0]; //double smallest= Double.POSITIVE_INFINITY; 
        double largest= x[0]; //double largest= Double.NEGATIVE_INFINITY;

        for (int i=0; i<x.length; i++) {
            x[i]= kbd.nextDouble();

            if (x[i] > largest) {
                largest = x[i];

            } else if (x[i] < smallest) {
                smallest = x[i];
            }
        }
        System.out.println("Smallest number: " + smallest + " Largest number: " + largest);
    }
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
anna
  • 15
  • 4

1 Answers1

2

When you initialize smallest and largest, you haven't put any values into x, so its elements are just the default values that the array was created with, i.e. zero.

Hence, you will only find a smaller smallest value if one is less than zero (or a larger largest value if one is greater than zero).

You should use the POSITIVE_INFINITY and NEGATIVE_INFINITY to initialize the values, since all values are smaller and larger than these respectively.


Alternatively, you can initalize smallest = largest = x[0] in the for loop when i == 0. However, the former approach is preferable, since it does not require checking i == 0 on every iteration.


Alternatively, you can move the first assignment out of the loop:

x[0] = smallest = largest = kbd.nextDouble();
for (int i = 1; i<x.length; i++) {
  x[i] = kbd.nextDouble();
  ...

This avoids checking i == 0 repeatedly, but you have to duplicate the kbd.nextDouble(). I'd still use the first approach.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Thanks, makes sense. I tried entering a negative number and noticed that it worked as soon as I posted but didn't understand why. :) – anna Apr 20 '16 at 23:28