0

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

我想出了第一部分,但对如何让我的程序显示最大和最小感到困惑。到目前为止,这是我的代码。我怎样才能让它也显示最小的输入?

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

3 回答 3

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);
}
于 2013-03-10T23:06:32.053 回答
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;
    }
}
于 2013-03-10T23:01:53.173 回答
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);
    }
}
于 2013-03-10T23:03:13.007 回答