-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrackifyCore.java
More file actions
112 lines (92 loc) · 2.96 KB
/
Copy pathTrackifyCore.java
File metadata and controls
112 lines (92 loc) · 2.96 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import java.io.*;
import java.util.*;
class Expense {
double amount;
String category;
String date;
Expense(double amount, String category, String date) {
this.amount = amount;
this.category = category;
this.date = date;
}
public String toString() {
return amount + "," + category + "," + date;
}
}
public class TrackifyCore {
static ArrayList<Expense> expenses = new ArrayList<>();
static final String FILE_NAME = "expenses.txt";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
loadExpenses();
while (true) {
System.out.println("\n1. Add Expense");
System.out.println("2. View Expenses");
System.out.println("3. Exit");
int choice = sc.nextInt();
switch (choice) {
case 1:
addExpense(sc);
break;
case 2:
viewExpenses();
break;
case 3:
saveExpenses();
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid choice");
}
}
}
static void addExpense(Scanner sc) {
try {
System.out.print("Enter amount: ");
double amount = sc.nextDouble();
sc.nextLine();
System.out.print("Enter category: ");
String category = sc.nextLine();
System.out.print("Enter date: ");
String date = sc.nextLine();
Expense exp = new Expense(amount, category, date);
expenses.add(exp);
System.out.println("Expense Added!");
} catch (Exception e) {
System.out.println("Invalid input!");
}
}
static void viewExpenses() {
if (expenses.isEmpty()) {
System.out.println("No expenses found.");
return;
}
for (Expense e : expenses) {
System.out.println(e.amount + " | " + e.category + " | " + e.date);
}
}
static void saveExpenses() {
try (PrintWriter pw = new PrintWriter(new FileWriter(FILE_NAME))) {
for (Expense e : expenses) {
pw.println(e);
}
} catch (IOException e) {
System.out.println("Error saving file");
}
}
static void loadExpenses() {
try (BufferedReader br = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
expenses.add(new Expense(
Double.parseDouble(data[0]),
data[1],
data[2]
));
}
} catch (IOException e) {
System.out.println("No previous data found.");
}
}
}