2014-02-21 22 views
3

我在Candy類中有一個名爲pricePerHundredGrams的方法,它應該做的是將變量價格乘以100.00,然後將該答案除以變量weightGrams,最後將結果返回給變量wammy。當在這個代碼的最後一個語句中調用變量wammy時,它應該將答案傳遞給返回結果。最終c1和c2應該顯示出這個結果......但是我得到了「每百克」的NaN。我的代碼有什麼問題?在java中獲得NaN的可能修復方法

public class whatever 
{ public static void main (String[] args) 
    { 
     processCandies(); 


     System.out.println("end of processing"); 

    } 

    public static void processCandies() 
    { 
     Candy c1 = new Candy("Hershey", 145, 4.35, 233); 
     Candy c2 = new Candy("Milky Way", 390, 2.66, 126); 

     System.out.println(c1); 
     System.out.println(c2); 
    } 

} 

class Candy 
{ 
    private String name; 
    private int calories; 
    private double price; 
    private double weightGrams; 

    double wammy = pricePerHundredGrams(price, weightGrams); 

/** 
    Constructor 
    @param name 
    @param calories 
    @param price 
    @param gram 
*/ 

public Candy(String n, int cal, double p, double wG) 
{ 
    name = n; 
    calories = cal; 
    price = p; 
    weightGrams = wG; 
} 

public String getName() 
{ 
    return name; 
} 

public int getCalories() 
{ 
    return calories; 
} 

public double getPrice() 
{ 
    return price; 
} 

public double getWeightGrams() 
{ 
    return weightGrams; 
} 

public double pricePerHundredGrams(double price, double weightGrams) 
{ 
    return (price * 100.00)/weightGrams; 
} 

public String toString() 
{ 
    String result; 
    result = name + "\n" + calories + " calories\n" + weightGrams + " grams\n" + wammy + " per hundred grams\n"; 
    return result; 
} 

}

+0

'weightGrams'值是...讓我猜,0? – m0skit0

+0

您是否嘗試過使用斷點調試代碼以在執行期間的某些點查看變量的值? – WOUNDEDStevenJones

+0

首先要解決的問題是:不要使用'double'作爲貨幣值。使用整數分(或其他),或使用'BigDecimal'。 –

回答

8

要初始化wammypricePerHundredGrams,但priceweightGrams結果尚未初始化,所以他們都0。對於double算術,0除以0NaN(它在數學上是不確定的)。

初始化wammypriceweightGrams在你的構造有效值:

public Candy(String n, int cal, double p, double wG) 
{ 
    name = n; 
    calories = cal; 
    price = p; 
    weightGrams = wG; 
    // Initialize wammy here. 
    wammy = pricePerHundredGrams(price, weightGrams); 
} 

此外,因爲它們已經實例變量,你並不需要通過priceweightGrams作爲參數傳遞給pricePerHundredGrams