0

The code is supposed to keep accepting numbers >-10 for as long as you enter them. Then when you are ready to exit you just enter anything other than a number and it is supposed to take the mean value of the sum of the numbers recorded and print the value, then exit.

When I enter a non-number (NaN) my program loops infinitely and I can't figure out how I can keep this from happening.

Program so far:

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;  

}
}
  • 1
    See http://stackoverflow.com/questions/1456566/how-do-you-test-to-see-if-a-double-is-equal-to-nan-in-java and http://stackoverflow.com/questions/8819738/why-does-double-nan-double-nan-return-false – nos Oct 08 '14 at 07:32

1 Answers1

3

By definition, NaN is not equal to anything, including itself. Thus

while(value != Double.NaN) {

doesn't work as you'd expect. Use Double.isNaN() instead.

When I enter a non-number (NaN)...

Just to be clear with the terminology, "a non-number" and not-a-number are not the same thing:

  • a non-number can be pretty much anything, e.g. an alphanumeric string;
  • a not-a-number (NaN) is a specific IEEE 754 floating-point value.
Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012