2013-03-10 130 views
0

我被分配到编写一个程序,读取的整数输入序列和打印 -the最小和最大的输入 -and的连号和奇数输入最小和最大的

我想通了输入在第一部分,但难以理解我如何让我的程序显示最大和最小。这是我的代码到目前为止。我怎样才能让它显示最小的输入?

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

你只需要两个跟踪变量('largest'和'smallest'),和你的循环内的两个比较。 – 2013-03-10 22:58:57

+0

请考虑“整齐”地格式化您的代码示例。特别是当它们涉及多层嵌套时,很难在没有缩进的情况下阅读它们。 – millimoose 2013-03-10 23:00:37

+0

查看'Math.min'和'Math.max'来帮助比较这些值并允许自动分配 – MadProgrammer 2013-03-10 23:05:06

回答

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

+1以获得优雅的解决方案。用于'Math.max'和'Math.min'的 – 2013-03-10 23:07:58

+0

+1 – wchargin 2013-03-11 03:44:39

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