最大阵列问题

时间:2016-03-20 00:16:28

标签: java arrays max min

所以我有一个我编写的程序,它找到了五个数字集的最大值和最小值。它大部分都有效,但是当我输入一组数字,如{5,6,7,8,9}时,它输出9作为最大值,但输出0表示最小值。任何想法或建议。     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);
}

}

2 个答案:

答案 0 :(得分:1)

将您的min默认为超出范围的数字(例如Double.MAX_VALUE)和maxDouble.MIN_VALUE。您也可以通过删除第二个循环来简化代码;您可以在一个循环中执行逻辑,然后使用Math.max(double, double)Math.min(double, double)。像,

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

答案 1 :(得分:0)

将您的min变量初始化为非零最大值。表示从控制台输入的最大值。