Possible fix for getting NaN in java

I have a method in a Candy class called pricePerHundredGrams, and what it should do is multiply the value of the price variable 100.00 and divide this answer by the weightGrams variable and finally return this result to the wammy variable. When the wammy variable is called in the most recent instruction of this code, it should pass a response to the return result. And ultimately c1 and c2 should also display this result ... but I get NaN for "one 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;
}

}

+3
source share
1 answer

wammy pricePerHundredGrams, price weightGrams , 0. double 0, 0, NaN ( ).

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

, , price weightGrams pricePerHundredGrams.

+8

All Articles