如何比较 10 个整数并在 Java 问题的 While 循环中获取最大和最小整数值

How to Compare 10 Integers and get the largest and smallest interger values in a While Loop in Java Issue

我正在尝试计算当用户输入 10 个不同的整数值时如何获得最小和最大的整数值。我得到了大部分但是,我不能得到最小值我只得到最大值。

import java.util.Scanner;

public class LargestAndSmallestValue
{

public static void main ( String[] args )
{


 Scanner input = new Scanner( System.in );

 int counter;
 int largest = 0;
 int smallest = 0;
 int number;

 number = 0;
 counter = 1;

 while ( counter <= 10)
 {
     System.out.printf(" Enter a Integer: ");
     number = input.nextInt();
     ++counter;

     if (number > largest)
     {
        largest = number; 
     }

     else

        if (number < smallest)
        {
           smallest = number;
        }

 }

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

 }
}

不是将最小值设置为 0,而是将其设置为作为输入读取的第一个数字。

boolean firstNum = true; // initialize this to act as a flag
while ( counter <= 10) {
    // your printf and input reading here 

    if (firstNum) {
        smallest = number;
        firstNum = false; // you only need to set the initial value once.
    }

    // your if statements here
}

像这样初始化你的临时变量:

int largest = Integer.MIN_VALUE;  //  2147483647
int smallest = Integer.MAX_VALUE; // -2147483648

你现在的做法是,如果输入的最小值是 17,但你的 smallest 变量被初始化为 0,smallest 永远不会改变。

我发现您的代码有两个潜在问题:

largest = 0;smallest = 0; 的初始值实际上可能大于或小于您的输入。例如,数字 1 - 10 中的 none 小于 0。您应该将这些变量初始化为极值,以保证您的输入在比较时将设置最大值或最小值。像

int largest = Integer.MIN_VALUE; //  or other smallest possible input (0)
int smallest = Integer.MAX_VALUE; // or other largest possible input (100000000)

下一个潜在的问题是你的比较逻辑。您的 if-else 结构假定输入不能同时是当前最大和最小的输入。考虑第一个输入何时最小:1, 2, 3, 4, 5, 6, 7, 8, 9, 10。在循环的第一次迭代中,1 > largest 为真,因此您无需费心检查 1 < smallest 是否也应该为真(如果您放入其他修复程序)。您在这里有两个选择:

  • 将您的条件检查更改为两个单独的检查(删除 else
  • 将最大和最小值设置为您的第一个输入以绕过这种极端情况。