2015-02-07 54 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。你是否將某個變量分配給某個地方?