我在糖果类中有一个名为 pricePerHundredGrams 的方法,它应该做的是将变量价格乘以 100.00 并将该答案除以变量 weightGrams,最后将该结果返回给变量 wammy。当在这段代码的最后第二条语句中调用变量 wammy 时,它应该传递答案以返回结果。最终 c1 和 c2 也应该显示该结果......但我得到“每百克”的 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;
}

}

最佳答案

您正在使用 wammy 的结果初始化 pricePerHundredGrams ,但 priceweightGrams 尚未初始化,因此它们都是 0 。对于 double 算术,0 除以 0 就是 NaN(在数学上是不确定的)。

wammyprice 在构造函数中具有有效值后初始化 weightGrams:

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

关于java - 在 Java 中获取 NaN 的可能修复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21940632/

10-12 02:37