因此,我开发了一个类,该类应该被另一个类使用。我开发的类如下:
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”,它代表“不是数字”。我查了一下,据说当有一个数学过程试图除以零或类似的东西时,就会发生这种情况。我再说一遍,我并不是在寻找答案,而是在正确的方向上插入我可能犯下的错误,我将不胜感激(我确信这是一个非常小而愚蠢的错误)。谢谢!
最佳答案
在构造函数中保存您的 milesPerGallon
变量:
public Car(double milesPerGallon)
{
this.milesPerGallon = milesPerGallon;
gas = 0.0;
}
关于java - 输出为 "NaN",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28377699/