Java 使用循环作为输入

Java 使用循环作为输入,java,loops,java-io,Java,Loops,Java Io,尝试获取5个不同温度读数的输入,并输出最低输入。我是java新手 System.out.println("Enter 5 temperature readings"); Scanner input = new Scanner(System.in); int count = 1; while (count <= 5){ int temp = input.nextInt(); if (temp < temp){ low = temp; } count++;

尝试获取5个不同温度读数的输入,并输出最低输入。我是java新手

System.out.println("Enter 5 temperature readings");
Scanner input = new Scanner(System.in);



int count = 1;
while (count <= 5){
  int temp = input.nextInt();
  if (temp < temp){
    low = temp;
  }

  count++;

}
System.out.println(------);
System.out.println(“输入5个温度读数”);
扫描仪输入=新扫描仪(System.in);
整数计数=1;

(count首先,您从未实例化过变量
low
。此外,我们需要
low
在循环之外,因此请确保这些变量在循环之外实例化,以便我们可以在输出
low
时使用它们。因此,让我们使用

int low = Integer.MAX_VALUE;
您可能会问“为什么整数.MAX_值?”这是因为1)变量
low
在用于比较之前必须初始化,2)我们不能使用0,因为如果温度不低于0,那么0将是低值!Integer.MAX_值是
int
可以容纳的最高值,因此远高于低温

接下来,让我们看看您的条件,我已经看到了一个问题:

if (temp < temp)
以便正确记录低温。接下来,一旦计算出
low
,您就可以使用

System.out.println(low);
这将为您提供五个输入值的低温

重构机会

如果要使代码更干净,我建议使用
for
循环,而不是
while
循环。这样,您的循环将成为

for (int i = 0; i < 5; i++)
{
    //your logic here
}
for(int i=0;i<5;i++)
{
//你的逻辑在这里
}

这意味着不需要使用
count
变量。

我将继续并假设这是所有相关代码。如果是这样,那么你有两个问题。第一个问题是,你从来没有宣布低。我建议在声明count之前或之后将low声明为int。第二个问题是,您正在将temp与自身进行比较。temp永远不会小于temp,所以本质上您正在创建一个永远不会运行的代码块。你应该写的是temp
System.out.println("Enter 5 temperature readings");
Scanner input = new Scanner(System.in);



int count = 1;
int low = input.nextInt(); //the lowest value cannot possible be higher than this.
while (count <= 4){ //made the loop shorter because one value was already read.
  int temp = input.nextInt();
  if (temp < low){
    low = temp;
  }

  count++;

}
System.out.println(low);
System.out.println(“输入5个温度读数”);
扫描仪输入=新扫描仪(System.in);
整数计数=1;
int low=input.nextInt()//最低值不能高于此值。

while(数一数你的问题是什么?你的代码出了什么问题?你的问题是什么?什么不起作用?为什么?你希望它做什么?你的问题在哪里?我如何让它输出最低的输入?我想输入5个不同的变量…5个不同的温度。例如。50,30,80,50,80。并让程序输出“30”
System.out.println("Enter 5 temperature readings");
Scanner input = new Scanner(System.in);



int count = 1;
int low = input.nextInt(); //the lowest value cannot possible be higher than this.
while (count <= 4){ //made the loop shorter because one value was already read.
  int temp = input.nextInt();
  if (temp < low){
    low = temp;
  }

  count++;

}
System.out.println(low);