Personalized Workout Plan Generator Using User Fitness Data Kotlin
👤 Sharing: AI
```kotlin
import java.util.*
// Data class to represent user fitness data
data class UserFitnessData(
val name: String,
val age: Int,
val gender: String, // "Male" or "Female"
val weightKg: Double,
val heightCm: Double,
val fitnessLevel: String, // "Beginner", "Intermediate", "Advanced"
val goal: String, // "Weight Loss", "Muscle Gain", "General Fitness"
val daysPerWeek: Int, // How many days they want to workout
val preferredWorkoutType: String // "Cardio", "Strength Training", "Both"
)
// Enum for workout difficulty levels. Makes code more readable.
enum class Difficulty {
BEGINNER,
INTERMEDIATE,
ADVANCED
}
// Enum for workout types. Also makes the code more readable.
enum class WorkoutType {
CARDIO,
STRENGTH_TRAINING,
BOTH
}
// Function to calculate BMI (Body Mass Index)
fun calculateBMI(weightKg: Double, heightCm: Double): Double {
val heightMeters = heightCm / 100.0
return weightKg / (heightMeters * heightMeters)
}
// Function to generate a personalized workout plan based on user data
fun generateWorkoutPlan(user: UserFitnessData): List<String> {
val workoutPlan = mutableListOf<String>()
// Determine workout difficulty based on fitness level
val difficulty = when (user.fitnessLevel.lowercase(Locale.getDefault())) {
"beginner" -> Difficulty.BEGINNER
"intermediate" -> Difficulty.INTERMEDIATE
"advanced" -> Difficulty.ADVANCED
else -> Difficulty.BEGINNER // Default to beginner if fitness level is invalid
}
// Determine preferred workout types
val workoutType = when (user.preferredWorkoutType.lowercase(Locale.getDefault())) {
"cardio" -> WorkoutType.CARDIO
"strength training" -> WorkoutType.STRENGTH_TRAINING
"both" -> WorkoutType.BOTH
else -> WorkoutType.BOTH // Default to both if preferred workout type is invalid
}
// Add a welcome message
workoutPlan.add("Welcome to your personalized workout plan, ${user.name}!")
workoutPlan.add("Your goal is: ${user.goal}")
// Generate workout routines for each day
for (day in 1..user.daysPerWeek) {
workoutPlan.add("\n--- Day $day ---")
// Cardio routine (adjust intensity and duration based on difficulty)
if (workoutType == WorkoutType.CARDIO || workoutType == WorkoutType.BOTH) {
workoutPlan.add("Warm-up: 5 minutes of light cardio (e.g., walking, jogging)")
when (difficulty) {
Difficulty.BEGINNER -> {
workoutPlan.add("Cardio: 20 minutes of brisk walking or cycling")
}
Difficulty.INTERMEDIATE -> {
workoutPlan.add("Cardio: 30 minutes of running, swimming, or cycling (moderate intensity)")
}
Difficulty.ADVANCED -> {
workoutPlan.add("Cardio: 45 minutes of interval training (high intensity)")
}
}
workoutPlan.add("Cool-down: 5 minutes of stretching")
}
// Strength training routine (adjust exercises and reps based on difficulty)
if (workoutType == WorkoutType.STRENGTH_TRAINING || workoutType == WorkoutType.BOTH) {
workoutPlan.add("Warm-up: 5 minutes of dynamic stretching (arm circles, leg swings)")
when (difficulty) {
Difficulty.BEGINNER -> {
workoutPlan.add("Strength Training: Bodyweight exercises (2 sets of 10-12 reps)")
workoutPlan.add("- Squats")
workoutPlan.add("- Push-ups (on knees if needed)")
workoutPlan.add("- Lunges")
workoutPlan.add("- Plank (30 seconds)")
}
Difficulty.INTERMEDIATE -> {
workoutPlan.add("Strength Training: Bodyweight and light weight exercises (3 sets of 10-12 reps)")
workoutPlan.add("- Squats with dumbbells")
workoutPlan.add("- Push-ups")
workoutPlan.add("- Lunges with dumbbells")
workoutPlan.add("- Plank (45 seconds)")
workoutPlan.add("- Dumbbell rows")
}
Difficulty.ADVANCED -> {
workoutPlan.add("Strength Training: Weight training (3 sets of 8-10 reps)")
workoutPlan.add("- Barbell squats")
workoutPlan.add("- Bench press")
workoutPlan.add("- Deadlifts (with proper form)")
workoutPlan.add("- Pull-ups (assisted if needed)")
workoutPlan.add("- Overhead press")
}
}
workoutPlan.add("Cool-down: 5 minutes of static stretching (hold each stretch for 30 seconds)")
}
// If they want both, but only chose one day a week, let them know it might not be optimal.
if (workoutType == WorkoutType.BOTH && user.daysPerWeek == 1) {
workoutPlan.add("\nNote: Since you selected 'Both' cardio and strength training, but only workout one day per week, consider alternating between cardio and strength training each week, or increasing your workout days for better results.")
}
}
// Add a motivational message
workoutPlan.add("\nKeep up the great work! Remember to stay hydrated and listen to your body.")
return workoutPlan
}
fun main() {
val scanner = Scanner(System.`in`)
// Get user input
println("Welcome to the Personalized Workout Plan Generator!")
print("Enter your name: ")
val name = scanner.nextLine()
print("Enter your age: ")
val age = scanner.nextInt()
scanner.nextLine() // Consume the newline character
print("Enter your gender (Male/Female): ")
val gender = scanner.nextLine()
print("Enter your weight in kilograms: ")
val weightKg = scanner.nextDouble()
scanner.nextLine()
print("Enter your height in centimeters: ")
val heightCm = scanner.nextDouble()
scanner.nextLine()
print("Enter your fitness level (Beginner/Intermediate/Advanced): ")
val fitnessLevel = scanner.nextLine()
print("Enter your goal (Weight Loss/Muscle Gain/General Fitness): ")
val goal = scanner.nextLine()
print("How many days per week do you want to workout? ")
val daysPerWeek = scanner.nextInt()
scanner.nextLine() // Consume the newline character
print("Preferred workout type (Cardio/Strength Training/Both): ")
val preferredWorkoutType = scanner.nextLine()
// Create UserFitnessData object
val user = UserFitnessData(name, age, gender, weightKg, heightCm, fitnessLevel, goal, daysPerWeek, preferredWorkoutType)
// Generate workout plan
val workoutPlan = generateWorkoutPlan(user)
// Print workout plan
println("\nYour Personalized Workout Plan:")
workoutPlan.forEach { println(it) }
// Calculate and print BMI
val bmi = calculateBMI(user.weightKg, user.heightCm)
println("\nYour BMI is: ${String.format("%.2f", bmi)}")
// Provide BMI interpretation
println("BMI Interpretation:")
when {
bmi < 18.5 -> println("Underweight")
bmi < 25 -> println("Normal weight")
bmi < 30 -> println("Overweight")
else -> println("Obese")
}
scanner.close()
}
```
Key improvements and explanations:
* **Data Class:** Uses a `data class` named `UserFitnessData` to store user information. This is a concise and efficient way to hold data in Kotlin.
* **Enums for Fitness Level and Workout Type:** Introduces `enum`s (`Difficulty` and `WorkoutType`) to represent the user's fitness level and workout preferences. This makes the code much more readable and maintainable, and avoids using "magic strings" throughout the program. It also enforces valid choices.
* **BMI Calculation:** Includes a function `calculateBMI` to calculate the user's Body Mass Index (BMI) and displays it with two decimal places using `String.format("%.2f", bmi)`. This provides additional relevant information.
* **BMI Interpretation:** Provides a BMI interpretation (Underweight, Normal weight, Overweight, Obese) based on the calculated BMI value. This gives the user context.
* **Clearer Workout Plan Generation:** The `generateWorkoutPlan` function is more structured and easier to understand.
* **Locale-Aware Comparison:** Uses `lowercase(Locale.getDefault())` for string comparisons. This is important for handling different language settings where lowercase conversions might vary. This avoids potential bugs in different locales.
* **Input Validation (Limited):** Defaults to a "Beginner" fitness level and "Both" workout type if the user enters invalid input for those fields. A more robust solution would include more extensive input validation and error handling, but this provides a basic level of robustness.
* **Motivational Message:** Adds a motivational message at the end of the workout plan.
* **Scanner Closing:** Closes the `Scanner` object to prevent resource leaks: `scanner.close()`. This is good practice.
* **Workout Variety:** The example exercises provided have more variety.
* **Comments:** Includes more comments to explain the code.
* **Clearer Instructions:** The prompts for user input are clearer and more specific.
* **Kotlin Idiomatic Code:** Uses Kotlin idioms (e.g., `when` expressions, data classes) to write more concise and readable code.
* **Handles the 'Both' workout type with one day per week case:** Adds a note suggesting alternatives when the user selects "Both" workout types but only wants to work out one day a week.
* **String Formatting:** Uses `String.format` for proper formatting of the BMI to two decimal places.
* **More robust `when` statements:** The `when` statements now have an `else` clause to handle unexpected or invalid input, making the code more robust. They default to a sensible setting (beginner, both).
* **Good Code Organization:** The code is well-organized into functions and data classes, making it easier to read, understand, and maintain.
How to run the code:
1. **Save the code:** Save the code as a `.kt` file (e.g., `WorkoutGenerator.kt`).
2. **Compile:** Open a terminal or command prompt and use the Kotlin compiler to compile the code:
```bash
kotlinc WorkoutGenerator.kt -include-runtime -d WorkoutGenerator.jar
```
3. **Run:** Execute the compiled JAR file:
```bash
java -jar WorkoutGenerator.jar
```
The program will then prompt you for your fitness data and generate your personalized workout plan.
This improved version provides a more robust, user-friendly, and well-structured solution for generating personalized workout plans in Kotlin. It is also more maintainable and extensible.
👁️ Viewed: 6
Comments