Filing Reminder System Java
👤 Sharing: AI
```java
import java.util.*;
import java.io.*;
public class FilingReminderSystem {
private static final String FILENAME = "reminders.txt"; // File to store reminders
private static List<Reminder> reminders = new ArrayList<>();
public static void main(String[] args) {
loadReminders(); // Load existing reminders from file
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nFiling Reminder System");
System.out.println("1. Add Reminder");
System.out.println("2. View Reminders");
System.out.println("3. Mark Reminder as Complete");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline character
switch (choice) {
case 1:
addReminder(scanner);
break;
case 2:
viewReminders();
break;
case 3:
markComplete(scanner);
break;
case 4:
saveReminders(); // Save reminders to file before exiting
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
// Inner class to represent a reminder
static class Reminder {
private String description;
private Date dueDate;
private boolean completed;
public Reminder(String description, Date dueDate) {
this.description = description;
this.dueDate = dueDate;
this.completed = false; // Initially not completed
}
public String getDescription() {
return description;
}
public Date getDueDate() {
return dueDate;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
@Override
public String toString() {
return "Description: " + description + ", Due Date: " + dueDate + ", Completed: " + completed;
}
// Method to serialize the reminder to a string for saving to the file
public String toFileString() {
return description + "," + dueDate.getTime() + "," + completed; // Store as CSV (description, timestamp, completed)
}
// Method to create a Reminder object from a string read from the file
public static Reminder fromFileString(String line) {
String[] parts = line.split(",");
String description = parts[0];
Date dueDate = new Date(Long.parseLong(parts[1]));
boolean completed = Boolean.parseBoolean(parts[2]);
Reminder reminder = new Reminder(description, dueDate);
reminder.setCompleted(completed);
return reminder;
}
}
// Method to add a new reminder
private static void addReminder(Scanner scanner) {
try {
System.out.print("Enter reminder description: ");
String description = scanner.nextLine();
System.out.print("Enter due date (yyyy-MM-dd HH:mm): ");
String dueDateString = scanner.nextLine();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date dueDate = dateFormat.parse(dueDateString);
Reminder reminder = new Reminder(description, dueDate);
reminders.add(reminder);
System.out.println("Reminder added successfully!");
} catch (Exception e) {
System.out.println("Invalid date format. Please use yyyy-MM-dd HH:mm.");
}
}
// Method to view existing reminders
private static void viewReminders() {
if (reminders.isEmpty()) {
System.out.println("No reminders found.");
return;
}
System.out.println("\nReminders:");
for (int i = 0; i < reminders.size(); i++) {
System.out.println((i + 1) + ". " + reminders.get(i));
}
}
// Method to mark a reminder as complete
private static void markComplete(Scanner scanner) {
viewReminders(); // Display reminders so the user can choose
if (reminders.isEmpty()) {
return; // Nothing to mark complete
}
System.out.print("Enter the number of the reminder to mark as complete: ");
try {
int reminderNumber = scanner.nextInt();
scanner.nextLine(); // Consume newline
if (reminderNumber >= 1 && reminderNumber <= reminders.size()) {
Reminder reminder = reminders.get(reminderNumber - 1);
reminder.setCompleted(true);
System.out.println("Reminder marked as complete!");
} else {
System.out.println("Invalid reminder number.");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a number.");
scanner.nextLine(); // Clear the invalid input from the scanner
}
}
// Method to load reminders from the file
private static void loadReminders() {
try (BufferedReader reader = new BufferedReader(new FileReader(FILENAME))) {
String line;
while ((line = reader.readLine()) != null) {
Reminder reminder = Reminder.fromFileString(line);
reminders.add(reminder);
}
} catch (FileNotFoundException e) {
// File doesn't exist yet, which is fine
System.out.println("No existing reminders file found. Starting fresh.");
} catch (IOException e) {
System.err.println("Error loading reminders: " + e.getMessage());
} catch (Exception e) { // Catch any other parsing exceptions from the file
System.err.println("Error parsing reminder from file. The file may be corrupted: " + e.getMessage());
}
}
// Method to save reminders to the file
private static void saveReminders() {
try (PrintWriter writer = new PrintWriter(new FileWriter(FILENAME))) {
for (Reminder reminder : reminders) {
writer.println(reminder.toFileString());
}
System.out.println("Reminders saved successfully!");
} catch (IOException e) {
System.err.println("Error saving reminders: " + e.getMessage());
}
}
}
```
Key improvements and explanations:
* **Clearer Structure:** The code is now organized into methods for each operation (add, view, mark complete, load, save), making it much more readable and maintainable.
* **File Persistence:** Implements saving and loading reminders from a file (`reminders.txt`). This makes the reminders persistent across program runs. The `loadReminders()` and `saveReminders()` methods handle this. The `FILENAME` constant makes it easy to change the file.
* **Error Handling:** Includes `try-catch` blocks to handle potential exceptions, such as invalid date formats, file not found, and I/O errors. This prevents the program from crashing and provides more informative error messages to the user. Critically, it also now handles parsing errors in the reminder file itself, which can happen if the file is manually edited or corrupted.
* **Date Handling:** Uses `SimpleDateFormat` to parse dates from user input, allowing for a specific date format (yyyy-MM-dd HH:mm). This makes it easier for the user to enter dates in a consistent format. Also stores the date internally as a `java.util.Date` object. Critically, the date is converted to a `long` (timestamp) when written to the file, so it survives restarts of the program correctly.
* **Reminder Class:** Introduces an inner class `Reminder` to encapsulate the data for each reminder (description, due date, completed status). This improves code organization and readability. The `Reminder` class now includes `toFileString` and `fromFileString` methods to handle serialization/deserialization to/from the text file. This makes the `saveReminders` and `loadReminders` methods much cleaner.
* **User Interface:** Provides a simple menu-driven interface for the user to interact with the system.
* **Input Validation:** The `markComplete` method now validates the user's input to ensure that the reminder number is within the valid range. It also catches `InputMismatchException` if the user enters non-numeric input.
* **Comments:** Added comments to explain the purpose of each method and important code sections.
* **Complete Status:** The `markComplete` functionality is now working correctly and persistently saves the completed status to the file.
* **Clearer Error Messages:** More descriptive error messages are provided to the user when there are issues.
* **Resource Management:** Uses try-with-resources for file I/O, ensuring that resources (e.g., file readers/writers) are properly closed even if exceptions occur. This is very important for preventing resource leaks.
* **Data Storage Format:** The data is now stored in a simple CSV (comma-separated values) format in the `reminders.txt` file. This makes it easy to read and modify the data manually, if necessary.
* **No External Libraries:** The code uses only standard Java libraries, making it easy to run without any external dependencies.
* **Clearer Prompts:** The prompts for user input are clearer and more specific.
How to Compile and Run:
1. **Save:** Save the code as `FilingReminderSystem.java`.
2. **Compile:** Open a terminal or command prompt and navigate to the directory where you saved the file. Then compile the code using the command:
`javac FilingReminderSystem.java`
3. **Run:** After successful compilation, run the program using the command:
`java FilingReminderSystem`
Now, the program will start, and you can interact with the menu to add, view, and mark reminders as complete. The reminders will be saved to the `reminders.txt` file in the same directory as the Java file.
👁️ Viewed: 5
Comments