[英]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);
}
}
}
如果我理解您的问题,则会简化您的代码。 您可以使用Math.min(double, double)
和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);
}
}
在第一个while循环中,代码陷入了无限循环。要解决此问题,请在break语句中添加。
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它表示:Max = 6.0 Min = 4.0,因为对于currentMax,它并没有考虑7;对于currentMin,它没有考虑2,因为它已经退出了while循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.