Please follow me here!

Sunday, November 18, 2012

Java Program : Fat Gram Calculator

Here's another program I want to share with you guys, which is simply a program that multiplies the number of grams of fat in food by nine, which gives off how many calories you earn upon eating a serving of that snack or provision. You need to enter the number of calories in the actual serving in that calculator and the number of grams of fat, and what will do is it will calculate the percentage and determine whether the food has a high amount of fat, at least 30%, or not.

This time, there are no notes taken on how this works.

import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class FatGramCalculator
{
    public static void main(String[] args)
    {
        String inputString;
        float totalCalories,
            fatGrams,
            caloriesFromFat,
            ratio,
            percent;
       
        DecimalFormat formatter = new DecimalFormat("##");
       
        inputString =
                JOptionPane.showInputDialog("How many calories are in the food item you want to study?");
        totalCalories = Float.parseFloat(inputString);
       
        inputString =
                JOptionPane.showInputDialog("How much fat is in the food item, in grams?");
        fatGrams = Float.parseFloat(inputString);
       
        caloriesFromFat = fatGrams * 9;
       
        ratio = caloriesFromFat / totalCalories;
       
        percent = ratio * 100;
       
        if (percent > 100)
            JOptionPane.showMessageDialog(null, "Invalid entry.");
       
        if (percent <= 100)
            JOptionPane.showMessageDialog(null, "Number of calories in food item: " + totalCalories +
                                        "\nNumber of grams of fat in food item: " + fatGrams +
                                        "\n\nPercent of calories of fat to total calories: " +
                                        (formatter.format(percent)) + "%");
       
        if (percent < 30)
            JOptionPane.showMessageDialog(null, "The food item is low in fat.");
       
        System.exit(0);
           
    }
}

Google+ Followers

Popular Posts by Gregory