-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskManager.java
More file actions
96 lines (81 loc) · 2.55 KB
/
TaskManager.java
File metadata and controls
96 lines (81 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.util.ArrayList;
import java.io.*;
public class TaskManager {
private ArrayList<Task> tasks;
private int nextId;
private final String FILE_NAME = "tasks.txt";
public TaskManager() {
tasks = new ArrayList<>();
loadTasks();
}
public void addTask(String title) {
Task task = new Task(nextId++, title);
tasks.add(task);
saveTasks();
System.out.println("Task added successfully!");
}
public void viewTasks() {
if (tasks.isEmpty()) {
System.out.println("No tasks available.");
return;
}
for (Task task : tasks) {
System.out.println(task);
}
}
public void markTaskCompleted(int id) {
for (Task task : tasks) {
if (task.getId() == id) {
task.markCompleted();
saveTasks();
System.out.println("Task marked as completed!");
return;
}
}
System.out.println("Task not found.");
}
public void deleteTask(int id) {
for (Task task : tasks) {
if (task.getId() == id) {
tasks.remove(task);
saveTasks();
System.out.println("Task deleted successfully!");
return;
}
}
System.out.println("Task not found.");
}
// Save tasks to file
private void saveTasks() {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME))) {
for (Task task : tasks) {
writer.write(task.toFileString());
writer.newLine();
}
} catch (IOException e) {
System.out.println("Error saving tasks.");
}
}
// Load tasks from file
private void loadTasks() {
File file = new File(FILE_NAME);
if (!file.exists()) {
nextId = 1;
return;
}
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
int maxId = 0;
while ((line = reader.readLine()) != null) {
Task task = Task.fromFileString(line);
tasks.add(task);
if (task.getId() > maxId) {
maxId = task.getId();
}
}
nextId = maxId + 1;
} catch (IOException e) {
System.out.println("Error loading tasks.");
}
}
}