←back to #AskDushyant

Real-World Use Case: Building a Simple To-Do List (Java, Python, and PHP)

As an exercise, I assigned the task of implementing a To-Do List—an everyday real-world application where core coding fundamentals like variables, loops, conditionals, and functions come into play. To give you a solid starting point, I’ve created a blueprint. The following code snippet allows users to add, delete, and view tasks using a command-line interface.

As mentioned earlier, you can choose any programming language to implement this. I’m providing code examples in Java, PHP, and Python to get you started.

To-Do List Application in Java

This Java implementation uses an array list to store the tasks and loops through user input to add, delete, and view tasks.

import java.util.ArrayList;
import java.util.Scanner;

public class TodoList {
    private static ArrayList<String> tasks = new ArrayList<>();

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

        while (!exit) {
            System.out.println("\nTo-Do List:");
            System.out.println("1. Add task");
            System.out.println("2. Delete task");
            System.out.println("3. View tasks");
            System.out.println("4. Exit");
            System.out.print("\nChoose an option: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume newline

            switch (choice) {
                case 1:
                    System.out.print("Enter the task: ");
                    String task = scanner.nextLine();
                    addTask(task);
                    break;
                case 2:
                    viewTasks();
                    System.out.print("Enter the task number to delete: ");
                    int taskIndex = scanner.nextInt();
                    deleteTask(taskIndex - 1);
                    break;
                case 3:
                    viewTasks();
                    break;
                case 4:
                    exit = true;
                    System.out.println("Goodbye!");
                    break;
                default:
                    System.out.println("Invalid option. Try again.");
            }
        }
        scanner.close();
    }

    private static void addTask(String task) {
        tasks.add(task);
        System.out.println("Task added.");
    }

    private static void deleteTask(int taskIndex) {
        if (taskIndex >= 0 && taskIndex < tasks.size()) {
            String removedTask = tasks.remove(taskIndex);
            System.out.println("Task '" + removedTask + "' deleted.");
        } else {
            System.out.println("Invalid task number.");
        }
    }

    private static void viewTasks() {
        if (tasks.isEmpty()) {
            System.out.println("No tasks available.");
        } else {
            System.out.println("Your tasks:");
            for (int i = 0; i < tasks.size(); i++) {
                System.out.println((i + 1) + ". " + tasks.get(i));
            }
        }
    }
}
How to Run:
  1. Compile: javac TodoList.java
  2. Run: java TodoList

To-Do List Application in PHP

PHP allows us to build a command-line application as well. This example uses a while loop to manage the To-Do List functionality.

<?php
$tasks = [];

function display_menu() {
    echo "\nTo-Do List:\n";
    echo "1. Add task\n";
    echo "2. Delete task\n";
    echo "3. View tasks\n";
    echo "4. Exit\n";
    echo "Choose an option: ";
}

function add_task($task) {
    global $tasks;
    $tasks[] = $task;
    echo "Task '$task' added.\n";
}

function delete_task($taskIndex) {
    global $tasks;
    if (isset($tasks[$taskIndex])) {
        $removed_task = $tasks[$taskIndex];
        unset($tasks[$taskIndex]);
        $tasks = array_values($tasks); // Re-index array
        echo "Task '$removed_task' deleted.\n";
    } else {
        echo "Invalid task number.\n";
    }
}

function view_tasks() {
    global $tasks;
    if (empty($tasks)) {
        echo "No tasks available.\n";
    } else {
        echo "Your tasks:\n";
        foreach ($tasks as $index => $task) {
            echo ($index + 1) . ". $task\n";
        }
    }
}

while (true) {
    display_menu();
    $choice = intval(fgets(STDIN));

    switch ($choice) {
        case 1:
            echo "Enter the task: ";
            $task = trim(fgets(STDIN));
            add_task($task);
            break;
        case 2:
            view_tasks();
            echo "Enter the task number to delete: ";
            $task_index = intval(fgets(STDIN)) - 1;
            delete_task($task_index);
            break;
        case 3:
            view_tasks();
            break;
        case 4:
            echo "Goodbye!\n";
            exit;
        default:
            echo "Invalid option. Try again.\n";
    }
}
?>
How to Run:
  1. Save as todo.php.
  2. Run in the terminal: php todo.php.

To-Do List Application in Python

Below is the Python implementation of the To-Do List application:

tasks = []

def display_menu():
    print("\nTo-Do List:")
    print("1. Add task")
    print("2. Delete task")
    print("3. View tasks")
    print("4. Exit")

def add_task(task):
    tasks.append(task)
    print(f"Task '{task}' added.")

def delete_task(task_index):
    try:
        removed_task = tasks.pop(task_index)
        print(f"Task '{removed_task}' deleted.")
    except IndexError:
        print("Invalid task number.")

def view_tasks():
    if tasks:
        print("\nYour tasks:")
        for idx, task in enumerate(tasks, start=1):
            print(f"{idx}. {task}")
    else:
        print("No tasks available.")

while True:
    display_menu()
    choice = input("\nChoose an option: ")

    if choice == '1':
        task = input("Enter the task: ")
        add_task(task)
    elif choice == '2':
        view_tasks()
        task_index = int(input("Enter the task number to delete: ")) - 1
        delete_task(task_index)
    elif choice == '3':
        view_tasks()
    elif choice == '4':
        print("Goodbye!")
        break
    else:
        print("Invalid choice, please select again.")
How to Run:
  1. Save as todo.py.
  2. Run in the terminal: python todo.py.

The above To-Do List program demonstrates the use of coding fundamentals across different languages—Java, PHP, and Python. Each of these programs:

  • Uses variables to store user input and tasks.
  • Utilizes loops to repeatedly show the menu and handle user choices.
  • Implements conditionals to execute code based on the user’s input (e.g., adding, deleting, or viewing tasks).
  • Uses functions to encapsulate the logic for different features like adding, deleting, and viewing tasks.

Above Coding exercise help, Understanding coding fundamentals to build useful and scalable applications. Whether you’re coding in Java, PHP, Python or any programming language, the core concepts of variables, loops, conditionals, and functions are indispensable. By mastering these concepts, you will be well-equipped to transition between programming languages, frameworks, and even tackle more advanced coding challenges in your development career.

#AskDushyant
#TechConcept #ProgrammingLanguage #Coding #PHP #Java #Python
Note: This example code is for illustration only. You must modify and experiment with the concept to meet your specific language version.

Leave a Reply

Your email address will not be published. Required fields are marked *