Search code examples
javaclasssuperclass

Output is "NaN"


So, I have developed a class that is suppose to be used by another class. The class I developed is as follows:

public class Car
{
private double milesPerGallon;
private double gas;

//Constructs a car with a given fuel efficiency
public Car(double milesPerGallon)
{
    gas = 0.0;
}

//Increases the amount of gas in the gas tank
public void addGas(double amount)
{
    gas = gas + amount;
}

//Decreases the amount of gas in the gas tank (due to driving and therefore consuming gas)
public void drive(double distance)
{
    gas = gas - (distance / milesPerGallon);
}

//Calculates range, the number of miles the car can travel until the gas tank is empty
public double range()
{
    double range;
    range = gas * milesPerGallon;
    return range;
}
}

The class that is suppose to use the class I developed is:

public class CarTester
{
/**
 * main() method
 */
public static void main(String[] args)
{
    Car honda = new Car(30.0);      // 30 miles per gallon

    honda.addGas(9.0);              // add 9 more gallons
    honda.drive(210.0);             // drive 210 miles

    // print range remaining
    System.out.println("Honda range remaining: " + honda.range());

    Car toyota = new Car(26.0);      // 26 miles per gallon

    toyota.addGas(4.5);              // add 4.5 more gallons
    toyota.drive(150.0);             // drive 150 miles

    // print range remaining
    System.out.println("Toyota range remaining: " + toyota.range());
}
}

Both classes compile successfully, however when the program is run I get the output "NaN," which stands for "Not a Number." I looked this up and supposedly it occurs when there is a mathematical process that attempts to divide by zero or something similar. I am not, I repeat, not looking for the answer, but a nudge in the right direction about where I might be making my mistake would be much appreciated (I'm sure it's a very small and stupid mistake). Thanks!


Solution

  • save your milesPerGallon variable at constructor:

    public Car(double milesPerGallon)
    {
       this.milesPerGallon = milesPerGallon;
       gas = 0.0;
    }