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);
}
}