Crafts daily plans balancing productivity, habits, and personal goals Kotlin

👤 Sharing: AI
```kotlin
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.Scanner

data class Task(
    val description: String,
    val startTime: LocalTime,
    val endTime: LocalTime,
    val category: String, // e.g., "Work", "Personal", "Habit", "Exercise"
    var completed: Boolean = false
)

fun main() {
    val scanner = Scanner(System.`in`)
    val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    val timeFormatter = DateTimeFormatter.ofPattern("HH:mm")

    println("Welcome to Your Daily Plan Creator!")

    // 1. Get Date
    print("Enter the date for the plan (yyyy-MM-dd): ")
    val dateString = scanner.nextLine()
    val date: LocalDate = try {
        LocalDate.parse(dateString, dateFormatter)
    } catch (e: Exception) {
        println("Invalid date format.  Using today's date.")
        LocalDate.now()
    }

    println("Creating plan for: ${date.format(dateFormatter)}")


    // 2. Define Goals for the Day
    print("Enter your main goals for today (comma-separated): ")
    val goals = scanner.nextLine().split(",").map { it.trim() }
    println("Your goals for today are: $goals")

    // 3. Create Tasks
    val tasks = mutableListOf<Task>()

    while (true) {
        println("\nEnter task details (or type 'done' to finish):")

        print("Description: ")
        val description = scanner.nextLine()
        if (description.lowercase() == "done") break

        print("Start time (HH:mm): ")
        val startTimeString = scanner.nextLine()
        val startTime: LocalTime = try {
            LocalTime.parse(startTimeString, timeFormatter)
        } catch (e: Exception) {
            println("Invalid time format.  Using 09:00.")
            LocalTime.of(9, 0)
        }


        print("End time (HH:mm): ")
        val endTimeString = scanner.nextLine()
        val endTime: LocalTime = try {
            LocalTime.parse(endTimeString, timeFormatter)
        } catch (e: Exception) {
            println("Invalid time format.  Using 10:00.")
            LocalTime.of(10, 0)
        }

        print("Category (Work, Personal, Habit, Exercise, etc.): ")
        val category = scanner.nextLine()

        tasks.add(Task(description, startTime, endTime, category))
    }

    // 4. Print the Daily Plan
    println("\n--- Daily Plan for ${date.format(dateFormatter)} ---")
    println("Goals: $goals\n")

    tasks.sortBy { it.startTime } // Sort tasks by start time

    for (task in tasks) {
        println(
            "${task.startTime.format(timeFormatter)} - ${task.endTime.format(timeFormatter)}: " +
                    "${task.description} (${task.category}) " +
                    if (task.completed) "[COMPLETED]" else ""
        )
    }

    // 5. Habit Tracking (Simple Example)
    println("\n--- Habit Tracking ---")
    val habitNames = mutableListOf<String>()
    while (true) {
        print("Enter a habit to track (or type 'done'): ")
        val habitName = scanner.nextLine()
        if (habitName.lowercase() == "done") break
        habitNames.add(habitName)
    }

    for (habit in habitNames) {
        print("Did you complete '$habit' today? (yes/no): ")
        val response = scanner.nextLine().lowercase()
        val completed = response == "yes"
        println("$habit completed: $completed")
    }


    // 6. Review and Completion (Basic)
    println("\n--- Review and Completion ---")
    for (i in tasks.indices) {
        print("Did you complete '${tasks[i].description}'? (yes/no): ")
        val response = scanner.nextLine().lowercase()
        tasks[i].completed = response == "yes"
    }

    println("\n--- Updated Daily Plan with Completion Status ---")
    for (task in tasks) {
        println(
            "${task.startTime.format(timeFormatter)} - ${task.endTime.format(timeFormatter)}: " +
                    "${task.description} (${task.category}) " +
                    if (task.completed) "[COMPLETED]" else ""
        )
    }


    println("\nHave a productive day!")
}
```

Key improvements and explanations:

* **Clearer Structure:**  The code is broken down into logical sections (Get Date, Define Goals, Create Tasks, Print Plan, Habit Tracking, Review Completion) making it easier to understand and maintain.
* **Data Class:** Uses a `Task` data class to hold task information. This makes the code more organized and readable. Data classes automatically provide `equals()`, `hashCode()`, `toString()` methods.
* **Date and Time Handling:**  Uses `java.time` (LocalDate, LocalTime, DateTimeFormatter) for date and time manipulation, which is the modern and recommended approach.  Error handling is included for invalid date/time formats.
* **User Input Validation:** Includes basic error handling for date and time input.  If the user enters an invalid format, it defaults to a sensible value.
* **Habit Tracking:**  Adds a simple habit tracking section.  It prompts the user for habits and whether they were completed.
* **Task Completion:** Implements a basic task completion feature. The user can mark tasks as complete, and this is reflected in the final output.
* **Sorting:** Sorts the tasks by start time for a more organized plan.
* **Clarity of Output:**  The output is formatted to be easily readable.
* **Comments:** Includes comments to explain different parts of the code.
* **Handles "done" Keyword:** Allows the user to enter "done" when adding tasks or habits to signal the end of the input process.
* **Category Field:** Added a `category` field to the `Task` class, allowing for better organization.
* **String Interpolation:** Uses Kotlin's string interpolation (`"${task.description}"`) which is more concise and readable than string concatenation.
* **Error Handling:**  Uses `try-catch` blocks to handle potential `DateTimeParseException` errors that can occur when parsing user-entered date and time strings. This prevents the program from crashing if the user enters an invalid format.
* **Mutability:** `tasks` is defined as a `mutableListOf<Task>`, allowing you to add new tasks dynamically.

How to Run:

1.  **Save:** Save the code as `DailyPlan.kt`.
2.  **Compile:** Open a terminal or command prompt and navigate to the directory where you saved the file. Compile the code using the Kotlin compiler: `kotlinc DailyPlan.kt -include-runtime -d DailyPlan.jar`
3.  **Run:** Execute the compiled program: `java -jar DailyPlan.jar`

This will run the program, and you'll be prompted to enter the date, goals, tasks, and habits. The program will then print out your daily plan, including task completion status and habit tracking.
👁️ Viewed: 6

Comments