174k views
1 vote
5. Create a Java application that asks a user to enter the

name of a menu item, the number of grams of fat, the
number of grams of protein, and the number of grams of
carbohydrates the item contains. The program should
display the total number of calories in the item, as well
as the percent of calories that come from fat. Use the
following information to perform the calculations: 1
gram fat = 9 calories; 1 gram carbohydrate = 4 calories;
1 gram protein = 4 calories.

User Verhagen
by
7.3k points

1 Answer

2 votes

Answer:

import java.util.Scanner;

public class MenuCalories {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Prompt the user for the name of the menu item

System.out.print("Enter the name of the menu item: ");

String itemName = scanner.nextLine();

// Prompt the user for the number of grams of fat, protein, and carbohydrates

System.out.print("Enter the number of grams of fat: ");

double fatGrams = scanner.nextDouble();

System.out.print("Enter the number of grams of protein: ");

double proteinGrams = scanner.nextDouble();

System.out.print("Enter the number of grams of carbohydrates: ");

double carbGrams = scanner.nextDouble();

// Calculate the total number of calories in the item

double totalCalories = (fatGrams * 9) + (proteinGrams * 4) + (carbGrams * 4);

// Calculate the percentage of calories that come from fat

double fatCalories = fatGrams * 9;

double percentFatCalories = (fatCalories / totalCalories) * 100;

// Display the results to the user

System.out.println("Total calories for " + itemName + ": " + totalCalories);

System.out.printf("Percentage of calories from fat: %.2f%%\\", percentFatCalories);

}

}

User Ulysses
by
6.9k points