2015-02-07 144 views
0

所以,我开发了一个假设被另一个类使用的类。我公司开发的类如下:输出是“NaN”

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”,代表“不是数字”。我查了一下,据推测,当有一个数学过程试图用零或类似的东西划分时就会发生这种情况。我不是,我再说一遍,不是在寻找答案,而是在正确的方向上推动我可能会犯我的错误的地方,我会非常感激(我敢肯定这是一个非常小而愚蠢的错误)。谢谢!

+0

不能快速测试这个,强制转换任何值到一个整数/浮点数......所以这意味着即使你在做toyota.range()...将它作为float/double值包装。 – Mayhem 2015-02-07 01:59:29

+1

看看你的'milesPerGallon'实例变量。哪里不对了? – Voicu 2015-02-07 02:00:51

+0

因为'honda.milesPerGallon'为0,因为你从来没有把它设置为任何东西。 (这就是为什么重要的是不要给出两个不同的东西同名 - 因为它会让你感到困惑) – immibis 2015-02-07 02:01:40

回答

2

保存milesPerGallon变量在构造函数:

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

好吧,我看到它是如何工作的,它输出了本田的正确答案,并且我在范围方法中创建了一个if-else语句,以便在范围为负的情况下输出0.0(发生在丰田)。感谢您的帮助! – user3727648 2015-02-07 02:15:29

1

你是不是在你的Car构造函数初始化milesPerGallon。所以它将0.0作为默认值。当一个数字除以0.0时,你会得到NaN

1

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

构造:

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

milesPerGallon用于以后,但从来没有初始化。

1

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

1

您未在构造函数中设置milesPerGallon,因此它被初始化为0.0。你是否将某个变量分配给某个地方?