Calorie Tracker App

“A tool to monitor daily calorie intake and support dietary goals.”

The Calorie Tracker App helps users track their daily calorie consumption and stay on top of their dietary goals. It provides an intuitive interface for logging food items, calculating total calories consumed, and notifying users when they exceed their daily calorie limit.

This project demonstrates problem-solving through user-friendly design and efficient coding techniques.

Problem Statement

What Problem Does It Solve?
Many individuals struggle to monitor their calorie intake, leading to challenges in maintaining a balanced diet or achieving health goals.

How Does It Solve It?
The Calorie Tracker App allows users to log their meals, automatically tracks calories, and provides real-time feedback on their remaining calorie allowance for the day.

Key Features

  1. User Registration
    • Allows users to enter their name and weight.
    • Automatically sets a personalized daily calorie limit based on user input.
  2. Dynamic Menu System
    • Provides options to log food, view stats, or exit.
    • Handles invalid inputs gracefully with clear error messages.
  3. Calorie Calculation
    • Updates the remaining calorie allowance with each logged meal.
    • Alerts users when they exceed their daily calorie limit.
  4. Activity Suggestions
    • When the user exceeds their calorie limit, the app suggests light or intense exercises to balance the extra intake.

Workflow or User Scenarios

Scenario 1:

  • The user eats an apple (70 calories).
  • They log the food into the app.
  • The app subtracts 70 from their daily calorie limit (e.g., 2500 – 70 = 2430 remaining).

Scenario 2:

  • The user eats a sandwich (630 calories).
  • The app updates the remaining calorie count to 1870.

Scenario 3:

The app alerts them, calculates the excess, and suggests compensatory exercises.

The user eats a sub (310 calories), exceeding their limit.

Code Implementation

The code for the Calorie Tracker App focuses on user interaction, calorie tracking, and input validation. Key features include:

User Registration:

System.out.print("Enter your name: ");
userName = scanner.nextLine();
System.out.print("Enter your weight: ");
userWeight = scanner.nextInt();
totalCalorieLimit = calculateCalorieLimit(userWeight);
remainingCalorieLimit = totalCalorieLimit;

Dynamic Menu System:

System.out.println("\nMenu:");
System.out.println("1. Add food intake");
System.out.println("2. View daily intake stats");
System.out.println("3. Exit");

Calorie Tracking and Alerts:

if (remainingCalorieLimit < 0) {
    exceededLimit = true;
    System.out.println("You have exceeded your daily calorie limit!");
}

Challenges and Learnings

During development, a key challenge was implementing robust input validation to handle unexpected or invalid user inputs. I learned how to use exception handling in Java to create a seamless user experience.

Future Improvements

Expanded Features: Add detailed nutritional breakdowns (e.g., protein, carbs, fats) for logged meals.

Persistent Storage: Save user data and calorie logs to a database for long-term tracking.

Mobile Interface: Create a mobile app version with a graphical interface for easier use.

Conclusion

The Calorie Tracker App is a practical tool for anyone looking to monitor their diet effectively. By providing calorie calculations, real-time tracking, and actionable feedback, it helps users stay on track with their health goals while demonstrating efficient and user-focused coding practices.

Below is the source code:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
  // Stores the name of the user.
  private static String userName;
  // Stores the weight of the user.
  private static int userWeight;
  // Stores the total daily calorie limit, initialized to 0.
  private static int totalCalorieLimit = 0;
  // Stores the remaining daily calorie limit.
  private static int remainingCalorieLimit;
  // Tracks whether the user has exceeded the daily calorie limit.
  private static boolean exceededLimit = false;

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Display welcome messages and instructions
    System.out.println("Welcome to the Calorie Tracker App!");
    System.out.println("Please register to get started.");

    // Check if the user is registered
    if (!isUserRegistered(scanner)) {
      // If not registered, prompt the user to register
      System.out.println("Please register to continue.");
      registerUser(scanner);
    }

    // Display the menu
    while (true) {
      System.out.println("\nMenu:");
      System.out.println("1. Add food intake");
      System.out.println("2. View daily intake stats");
      System.out.println("3. Exit");
      try {
        System.out.print("Enter your choice: ");
        int choice = scanner.nextInt();
        // Consume newline character
        scanner.nextLine();
        // Switch statement to handle user menu choice:
        switch (choice) {
          // - Case 1: Adds food intakes by calling the addFoodIntake() method.
          case 1:
            addFoodIntake(scanner);
            break;
          // - Case 2: Displays daily intakes statistics by calling the
          // viewDailyIntakeStats() method.
          case 2:
            viewDailyIntakeStats();
            break;
          // - Case 3: Exits the program with a thank you message if the user chooses to
          // exit.
          case 3:
            System.out.println("Thank you for using the Calorie Tracker App!");
            System.exit(0);
            break;
          // - Default: Prints an error message for invalid menu choices.
          default:
            System.out.println("Invalid choice. Please try again.");
        }
      } catch (InputMismatchException e) {
        System.out.println("Invalid choice. Please enter a number.");
        // Clear the scanner buffer
        scanner.nextLine();
      }
    }
  }

  // Checks if the user is registered by verifying if the userName is not null and
  // the userWeight is greater than 0.
  private static boolean isUserRegistered(Scanner scanner) {
    return userName != null && userWeight > 0;
  }

  // Registers the user by prompting them to enter their name and weight,
  // calculates the calorie limit based on the weight, and stores the user's
  // information.
  private static void registerUser(Scanner scanner) {
    System.out.print("Enter your name: ");
    userName = scanner.nextLine();
    System.out.print("Enter your weight (in lbs): ");
    userWeight = scanner.nextInt();
    scanner.nextLine(); // Consume newline character
    calculateCalorieLimit();
  }

  private static void calculateCalorieLimit() {
    // Calculate total daily calorie limit as 15 times the user's weight
    totalCalorieLimit = userWeight * 15;
    remainingCalorieLimit = totalCalorieLimit;
  }

  // Calculates the total daily calorie limit based on the user's weight.
  private static void addFoodIntake(Scanner scanner) {
    System.out.print("Enter the food you ate: ");
    String food = scanner.nextLine();
    System.out.print("Enter the number of calories in " + food + ": ");
    int calories = scanner.nextInt();
    scanner.nextLine(); // Consume newline character

    // Subtract user input calories from the remaining calorie limit
    remainingCalorieLimit -= calories;

    // Checks if the remaining calorie limit is negative, sets exceededLimit if
    // true, and displays the excess calorie message.
    if (remainingCalorieLimit < 0) {
      exceededLimit = true;
      int excessCalories = Math.abs(remainingCalorieLimit);
      System.out.println("You have exceeded your daily calorie limit by " + excessCalories + " calories.");
      System.out.println("Consider engaging in a light workout (e.g., walking) for approximately "
          + (excessCalories / 3) + " minutes");
      System.out.println("or an intense workout (e.g., running or weight lifting) for approximately "
          + (excessCalories / 8) + " minutes");
    }
    // Displays the remaining calorie limit if it is not negative.
    else {
      System.out.println("Remaining calorie limit: " + remainingCalorieLimit);
    }
  }

  // Displays the daily intakes statistics, including the total and remaining
  // calorie limits.
  private static void viewDailyIntakeStats() {
    System.out.println("Daily intake stats:");
    System.out.println("Total calorie limit: " + totalCalorieLimit);
    System.out.println("Remaining calorie limit: " + remainingCalorieLimit);
  }
}