0
只要你輸入密碼,代碼應該保持接受> -10的數字。然後,當您準備退出時,只需輸入除數字以外的任何內容,並且應該記錄所記錄數字總和的平均值並打印該值,然後退出。(Java)當我輸入一個非數字(NaN)時,我的程序會無限循環到應該退出的地方。
當我輸入一個非數字(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;
}
}
請參閱http://stackoverflow.com/questions/1456566/how-do-you-test-to-see-if-a-double-is-equal-to-nan-in-java和http: //stackoverflow.com/questions/8819738/why-does-double-nan-double-nan-return-false – nos 2014-10-08 07:32:30