221k views
4 votes
Java Eclipse Homework Calories

Package : chall12A
Class : Calories

Use a “while loop” in the code to solve the following problem:

Over a 14-day period, calculate the total number of calories that the user consumed.
Use the following information to create the necessary code. You will use a while loop in this code.

1. The following variables will need to be of type “int”:
• day
• calories
• totalCalories
1. Show a title on the screen for the program.
2. Ask the user if they want to run the program.
3. Initialize (give values) to those variables that need starting values.
4. If their answer is a capital or lowercase ‘Y’, do the following:
• Use a while loop to loop through the days.
• Ask the user for the number of calories he/she consumed on each day. Please • include the day number in your question. Example: “How many calories did you consume on day 1?”
Include the calculation to keep a running total of the calories consumed.
1. After 14 days, the code should fall out of the loop. Include a print statement that looks like this: “After 14 days, you consumed ____ calories.” (Of course, the computer will need to fill in the total number.)
2. Include an “else” so that there is an appropriate response if the user decides not to run the program.

1 Answer

3 votes

import java.util.Scanner;

public class Calories {

public static void main(String[] args) {

int day = 0, calories = 0, totalCalories = 0;

System.out.println("Title");

Scanner myObj = new Scanner(System.in);

System.out.println("Do you want to continue?");

String start = myObj.nextLine();

if (start.toLowerCase().equals("y")){

while (day < 14){

day += 1;

System.out.println("How many calories did you consume on day " +day + ":");

calories = myObj.nextInt();

totalCalories += calories;

}

System.out.println("After 14 days, you consumed " + totalCalories + " calories");

}

else{

System.out.println("Goodbye!");

}

}

I hope this helps!

User Honey
by
5.6k points