只要您输入代码,代码就会继续接受数字> -10。然后,当您准备退出时,只需输入除数字以外的任何内容,它应该取记录数字之和的平均值并打印该值,然后退出。
当我输入一个非数字(NaN)时,我的程序无限循环,我无法弄清楚如何防止这种情况发生。
到目前为止的计划:
package project1;
import java.util.Scanner;
public class mean
{
public static void main(String[] args)
{
System.out.println("Enter the Temperature: ");
Scanner input = new Scanner(System.in);
double value=0.0;
double sum=0;
int i=0;
//This infinitely loops when a non Double value is entered. WHY!?!?!?
while(value != Double.NaN) {
value = averageTemperature(input, -10);
sum += value;
i++;
System.out.println("I've been here " + i + " time(s)");
if (value == Double.NaN){
break;
}
}
double mean = sum / i;
System.out.println("The average temperature is: " + mean);
}
public static double averageTemperature(Scanner input, double lowestTemp)
{
double temp = 0.0;
if (input.hasNextDouble()) {
temp = input.nextDouble();
if(temp >= lowestTemp){
return temp;
}
else if (temp < lowestTemp)
{
System.out.println("Invalid temperature. Please Re-enter: ");
return averageTemperature(input,lowestTemp);
}
}
return Double.NaN;
}
}
答案 0 :(得分:3)
根据定义,NaN
is not equal to anything, including itself。因此
while(value != Double.NaN) {
并不像你期望的那样工作。请改用Double.isNaN()
。
当我输入非数字(NaN)......
时
只是要明确术语,&#34;非数字&#34;和非数字不是一回事: