在 Java 中,我如何构造一个 for 循环来找到我输入的十个值的最大值和最小值。我目前没有收到该程序的输出

In Java how do i structure a for loop to find me the max and min of ten values entered. I am currently recieveing not output from this program

我想要做的是从用户那里接收到十个小数点后十位的值。然后我想找到最大值和最小值,并只显示它们。我尝试了很多不同的配置,这个最有逻辑,但我仍然无法获得任何类型的输出。

import java.util.Scanner;

public class Lab5b     
{

    public static void main(String[] args) 
    {

        Scanner in = new Scanner(System.in);


        for (int counter = 0; counter <= 10; counter++ )
        {
            double currentMin = in.nextDouble();

                while (in.hasNextDouble())
                {
                    double input = in.nextDouble();
                    if (input < currentMin)
                    {
                        currentMin = input;
                    }
                }

            double currentMax = in.nextDouble();

                while (in.hasNextDouble())
                {
                    double input = in.nextDouble();
                    if (input > currentMax)
                    {
                        currentMax = input;
                    }
                }

                System.out.println(currentMax);
                System.out.print(currentMin);

        }   

    }

}

代码在第一个while循环中陷入死循环 要解决此问题,请放入中断语句。

if (input < currentMin){
    currentMin = input;
    break;
}

并且也在另一个 if 语句中。

if (input > currentMax){
    currentMax = input;
    break;
}

否则它总是在第一个 while 循环中不断请求新的输入。

同时更改:

System.out.print(currentMin);

System.out.println(currentMin);

换行。

但是如果我输入

5 7 4个 2个 6个 它说: 最大值 = 6.0 最小 = 4.0 因为它没有考虑 7 考虑 currentMax 和 2 不考虑 currentMin 因为它已经退出了 while 循环。

如果我理解你的问题,我会简化你的代码。您可以使用 Math.min(double, double) and Math.max(double, double)。第一个值是 0,因此您希望测试为 <(而不是 <=),您可以检查循环条件中的 nextDouble() 条件。这可能看起来像

Scanner in = new Scanner(System.in);
int values = 10;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (int counter = 0; counter < values && in.hasNextDouble(); counter++) {
    double v = in.nextDouble();
    min = Math.min(min, v);
    max = Math.max(max, v);
}
System.out.println("min: " + min);
System.out.println("max: " + max);

这是可能的解决方案之一...

import java.util.Scanner;

public class MinMaxForLoop {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        double min = Double.MAX_VALUE;
        double max = Double.MIN_VALUE;
        double current;

        System.out.println("Enter 10 double values:");
        for (int i = 0; i < 10; i++) {
            System.out.print((i+1) + ". -> ");
            current = input.nextDouble();
            if(current < min)
                min = current;
            else if(current > max)
                max = current;
        }
        System.out.println("Min: " + min);
        System.out.println("Max: " + max);
    }

}