Java Code Examples: OOP Concepts and File I/O

Circle Class Usage Example (Chap13Part6)

public class Chap13Part6 {
    public static void main(String[] args) {
        // Assuming a Circle class exists with constructor Circle(x, y, radius)
        Circle c1 = new Circle(50, 50, 10);
        System.out.println(c1.getX());
        System.out.println(c1.getY());
        System.out.println(c1.getRadius());
    }
}

Employee and Manager Info Display (Chap13Part2)

public class Chap13Part2 {
    public static void main(String[] args) {
        // Assuming Employee and Manager classes exist
        Employee e1 = new Employee("Smith", 30000);
        Manager m1 = new Manager("Brown", 50000, "IT");
        System.out.println(e1.displayEmpInfo());
        System.out.println(m1.displayEmpInfo());
    }
}

Command-Line To-Do List Application (Chap17Part7)

import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;

public class Chap17Part7 {
    static String fileName = "c:\\data\\todo.txt"; // Note: Double backslash for Java String literal

    public static void main(String[] args) throws IOException {
        int menuItem = -1;
        while (menuItem != 0) {
            menuItem = menu();
            switch (menuItem) {
                case 1:
                    showList();
                    break;
                case 2:
                    addItem();
                    break;
                case 3:
                    removeItem();
                    break;
                case 0:
                    System.out.println("Exiting program.");
                    break;
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }
    }

    static int menu() {
        int choice;
        Scanner input = new Scanner(System.in);
        System.out.println("\n--- Main Menu ---");
        System.out.println("0. Exit the program");
        System.out.println("1. Display to-do list");
        System.out.println("2. Add item to to-do list");
        System.out.println("3. Remove item from to-do list");
        System.out.println();
        System.out.print("Enter your choice: ");
        // Basic input validation could be added here
        choice = input.nextInt();
        // input.nextLine(); // Consume newline left-over
        return choice;
    }

    static void showList() {
        System.out.println("\n--- To-Do List ---");
        try (Scanner inFile = new Scanner(new FileReader(fileName))) { // Use try-with-resources
            String line;
            int number = 1;
            if (!inFile.hasNextLine()) {
                System.out.println("The list is empty.");
            }
            while (inFile.hasNextLine()) {
                line = inFile.nextLine();
                System.out.println(number + ". " + line);
                ++number;
            }
            System.out.println();
        } catch (FileNotFoundException fnfe) {
            System.out.println("To-do list file not found. Add an item to create it.");
        } catch (IOException ioe) {
            System.out.println("Error reading file: " + ioe.getMessage());
        }
    }

    static void addItem() {
        System.out.println("\n--- Add Item ---");
        try (PrintWriter outFile = new PrintWriter(new FileWriter(fileName, true)); // Use try-with-resources
             Scanner input = new Scanner(System.in)) {
            System.out.print("Enter the item to add: ");
            String item = input.nextLine();
            if (item != null && !item.trim().isEmpty()) {
                 outFile.println(item);
                 System.out.println("Item added.");
            } else {
                 System.out.println("Cannot add an empty item.");
            }
        } catch (IOException ioe) {
            System.out.println("Error writing to file: " + ioe.getMessage());
        }
    }

    static void removeItem() {
        showList(); // Show list with numbers first
        ArrayList<String> items = new ArrayList<>(); // Use generics
        int number = 1;
        int choice = -1;

        // Read existing items into memory
        try (Scanner inFile = new Scanner(new FileReader(fileName))) {
            while (inFile.hasNextLine()) {
                items.add(inFile.nextLine());
            }
        } catch (FileNotFoundException fnfe) {
            System.out.println("No items to remove. The list is empty or file not found.");
            return;
        } catch (IOException ioe) {
            System.out.println("Error reading file: " + ioe.getMessage());
            return;
        }

        if (items.isEmpty()) {
             System.out.println("The list is currently empty. Nothing to remove.");
             return;
        }

        // Get user choice
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of the item to remove (or 0 to cancel): ");
        // Basic input validation
        if (input.hasNextInt()) {
             choice = input.nextInt();
        } else {
             System.out.println("Invalid input. Please enter a number.");
             input.next(); // Consume invalid input
             return;
        }

        if (choice <= 0 || choice > items.size()) {
            System.out.println("Invalid item number or cancellation requested.");
            return;
        }

        // Remove the selected item (adjusting for 0-based index)
        String removedItem = items.remove(choice - 1);
        System.out.println("Removed: " + removedItem);

        // Write the modified list back to the file
        try (PrintWriter outFile = new PrintWriter(new FileWriter(fileName))) { // Overwrite the file
            for (String item : items) {
                outFile.println(item);
            }
        } catch (IOException ioe) {
            System.out.println("Error writing updated list to file: " + ioe.getMessage());
            // Consider how to handle partial writes or recovery
        }
    }
}

Manager Class Definition (Extends Employee)

// Assuming an Employee class exists with constructor Employee(name, salary)
// and methods getName(), getSalary(), displayEmpInfo(), raise(double percent)
// and salary field is accessible (e.g., protected or via setter)
public class Manager extends Employee {
    private String department;

    Manager(String n, int s, String d) {
        super(n, s); // Call Employee constructor
        this.department = d;
    }

    public String getDepartment() {
        return department;
    }

    // Overriding the displayEmpInfo method from Employee
    @Override // Good practice to use Override annotation
    public String displayEmpInfo() {
        String empinfo = super.displayEmpInfo(); // Call base class method
        // Ensure proper formatting from base class method
        return empinfo + "Department: " + department + "\n";
    }

    // Example method - Note: Directly modifying another object's field might break encapsulation
    // A better approach might be a method within Employee to change salary.
    public void changeSalary(Employee e, double amount) {
        // This assumes 'salary' in Employee is accessible (e.g., protected or public)
        // Or preferably, Employee has a setSalary(double amount) method.
        // e.setSalary(amount); // Preferred if setter exists
        e.salary = amount; // Direct access (less ideal)
    }
}

Employee and Manager Object Interaction (Chap13Part1)

public class Chap13Part1 {
    public static void main(String[] args) {
        // Assuming Employee and Manager classes are defined as above/elsewhere
        Employee e1 = new Employee("Brown", 30000);
        System.out.println(e1.getName() + ": " + e1.getSalary());

        Manager m1 = new Manager("Smith", 50000, "Sales");
        System.out.println(m1.getName());
        System.out.println(m1.getSalary());
        System.out.println(m1.getDepartment());

        // Assuming Employee class has a raise(double percent) method
        // m1.raise(0.20); // Raise salary by 20%
        // System.out.println("New Salary: " + m1.getSalary());
    }
}