java - 输出为 "NaN"

标签 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”,它代表“不是数字”。我查了一下,据说当有一个数学过程试图除以零或类似的东西时,就会发生这种情况。我再说一遍,我并不是在寻找答案,而是在正确的方向上插入我可能犯下的错误,我将不胜感激(我确信这是一个非常小而愚蠢的错误)。谢谢!

最佳答案

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

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

关于java - 输出为 "NaN",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28377699/

相关文章:

java - 在java中运行二进制文件时出现异常错误

python - 如何在类中调用函数?

java - 子类和父类(super class)中的同名变量

java - HDFS 文件系统 - 如何获取目录中特定文件的字节数

Java HttpServletRequest isUserInRole 无法正常工作(根据请求安全性)servlet api 2.4

python - 将我的函数变成一个类

class - 德尔福 2009 : Component Object property default value

java - 我想使用在父类(super class)中创建的数组中的子类中的字段

java - 方法必须调用 Netbeans 中的 super() 错误

java - 如何将类型保存为变量并在 cast 中使用它