Question

I have a method in the Candy Class named pricePerHundredGrams and what it is supposed to do is multiply the variable price times 100.00 and divide that answer by the variable weightGrams, and finally return that result to the variable wammy. When the variable wammy is called for in the very 2nd last statement of this code, it is supposed to pass the answer to return result. And ultimately c1 and c2 should display that result as well...but I get NaN for "per hundred grams". What is wrong with my code?

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;
}

}

Was it helpful?

Solution

You are initializing wammy with the result of pricePerHundredGrams, but price and weightGrams haven't been initialized yet, so they're both 0. For double arithmetic, 0 divided by 0 is NaN (it's indeterminate in math).

Initialize wammy after price and weightGrams have valid values in your constructor:

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);
}

Additionally, since they are already instance variables, you don't need to pass price and weightGrams as parameters to pricePerHundredGrams.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top