最小和最大的输入

时间:2013-03-10 22:57:11

标签: java max minimum

我被分配编写一个读取整数输入和打印序列的程序 - 最小和最大的输入 - 以及偶数和奇数输入的数量

我想出了第一部分,但我很难知道如何让我的程序显示最大和最小的程序。到目前为止这是我的代码。如何让它显示最小的输入?

public static void main(String args[])
{
      Scanner a = new Scanner (System.in);
      System.out.println("Enter inputs (This program calculates the largest input):");

      double largest = a.nextDouble();
      while (a.hasNextDouble())
      { 
          double input = a.nextDouble();
          if (input > largest)
          {
              largest = input;
          }
      }


      System.out.println(largest);
}

3 个答案:

答案 0 :(得分:8)

最简单的解决方案是使用Math.minMath.max

之类的内容
double largest = a.nextDouble();
double smallest = largest;
while (a.hasNextDouble()) {
    double input = a.nextDouble();
    largest = Math.max(largest, input);
    smallest = Math.min(smallest, input);
}

答案 1 :(得分:2)

double largest = a.nextDouble();
double smallest = largest;
while (a.hasNextDouble()) {
    double input = a.nextDouble();
    if (input > largest) {
        largest = input;
    }
    if (input < smallest) {
        smallest = input;
    }
}

答案 2 :(得分:1)

以相同的方式跟踪最小值。

public static void main(String args[])
{
    Scanner a = new Scanner (System.in);
    System.out.println("Enter inputs (This program calculates the largest and smallest input):");

    double firstInput = a.nextDouble();
    double largest = firstInput;
    double smallest = firstInput;
    while (a.hasNextDouble())
    { 
        double input = a.nextDouble();
        if (input > largest)
        {
            largest = input;
        }
        if (input < smallest)
        {
            smallest = input;
        }
    }

    System.out.println("Largest: " + largest);
    System.out.println("Smallest: " + smallest);
    }
}