所以,我开发了一个假设被另一个类使用的类。我公司开发的类如下:输出是“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”,代表“不是数字”。我查了一下,据推测,当有一个数学过程试图用零或类似的东西划分时就会发生这种情况。我不是,我再说一遍,不是在寻找答案,而是在正确的方向上推动我可能会犯我的错误的地方,我会非常感激(我敢肯定这是一个非常小而愚蠢的错误)。谢谢!
不能快速测试这个,强制转换任何值到一个整数/浮点数......所以这意味着即使你在做toyota.range()...将它作为float/double值包装。 – Mayhem 2015-02-07 01:59:29
看看你的'milesPerGallon'实例变量。哪里不对了? – Voicu 2015-02-07 02:00:51
因为'honda.milesPerGallon'为0,因为你从来没有把它设置为任何东西。 (这就是为什么重要的是不要给出两个不同的东西同名 - 因为它会让你感到困惑) – immibis 2015-02-07 02:01:40