输出为“NaN”

时间:2015-02-07 01:56:56

标签: java class superclass

所以,我开发了一个类,假设被另一个类使用。我开发的课程如下:

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;
}
}

假设使用我开发的类的类是:

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());
}
}

两个类都编译成功,但是当程序运行时,我得到输出“NaN”,代表“非数字”。我看了这个,据说当有一个数学过程试图除以零或类似的东西时就会发生这种情况。我不是,我重申,不是在寻找答案,而是在正确的方向上推动我可能犯错误的地方将非常感激(我确信这是一个非常小而且愚蠢的错误)。谢谢!

5 个答案:

答案 0 :(得分:2)

在构造函数中保存milesPerGallon变量:

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

答案 1 :(得分:1)

您没有在milesPerGallon构造函数中初始化Car。因此它将0.0作为默认值。当一个数字除以0.0时,您将获得NaN

答案 2 :(得分:1)

需要将

milesPerGallon初始化为构造函数参数。

构造

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

milesPerGallon稍后使用,但从未初始化。

答案 3 :(得分:1)

好像你没有初始化milesPerGallon。您在构造函数中接受的变量与您在类顶部初始化的私有变量不同。通常人们喜欢使用像公共汽车(aMilesPerGallon)这样的东西来确保他们知道差异。或者作为我在输入时发布的答案说,this.milesPerGallon引用了类顶部的变量。

答案 4 :(得分:1)

您没有在构造函数中设置milesPerGallon,因此它被初始化为0.0。你在某个地方用某个变量划分某些东西吗?