简体   繁体   中英

min max in array issue

So I have a program I wrote that finds the max and min value of a five number set. It works for the most part but when I enter a set of numbers like {5,6,7,8,9} then it outputs 9 as the max, but outputs 0 for the min. Any thoughts or suggestions. import java.util.Scanner;

public class MinMax {
  public static void main (String [] args) {
  @SuppressWarnings("resource")
  Scanner in = new Scanner (System.in);
  final int NUM_ELEMENTS = 5;
  double[] userVals = new double[NUM_ELEMENTS];
  int i = 0;
  double max = 0.0;
  double min = 0.0;

  System.out.println("Enter five numbers.");
  System.out.println();

  while (i < NUM_ELEMENTS) {
      System.out.println("Enter next number: ");
      userVals[i] = in.nextDouble();
      i++;
      System.out.println();
  }

  for (i = 0; i < userVals.length; i++) {
     if (userVals[i] > max) {
         max = userVals[i];
     }
         else if (userVals[i] < min) {
             min = userVals[i];
     }
  }
  System.out.println("Max number: " + max);
  System.out.println("Min number: " + min);
}

}

Default your min to a number out of range (like Double.MAX_VALUE ), and max to Double.MIN_VALUE . You might also simplify your code by removing the second loop; you can perform the logic in one loop and you might use Math.max(double, double) and Math.min(double, double) . Something like,

Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
System.out.println("Enter five numbers.");
System.out.println();
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < NUM_ELEMENTS; i++) {
    System.out.println("Enter next number: ");
    userVals[i] = in.nextDouble();
    min = Math.min(min, userVals[i]);
    max = Math.max(max, userVals[i]);
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);

Intialize your min variable to non-zero max value. Means max value that you can have in your input from console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM