-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainMenu.java
More file actions
336 lines (290 loc) · 14.4 KB
/
Copy pathMainMenu.java
File metadata and controls
336 lines (290 loc) · 14.4 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import java.util.*;
import java.io.*;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.File;
import java.io.BufferedReader;
import java.io.IOException;
public class MainMenu {
static Scanner sc = new Scanner(System.in);// sets scanner for user input for the menu
static ArrayList<HashMap<String, String>> logs = new ArrayList<>();//used to store the log entries
static final String FILE_NAME = "log.json"; //Log file name
public static void main(String[] args) {
loadLogsFromFile(); // loads the logs from previously saved file on startup
while(true) {//continuous loop
System.out.println("\n--- Emotional Wellness Tracker ---");//menu line output
System.out.println("1. Log Feelings");
System.out.println("2. View Logs");
System.out.println("3. View Emotional Wellness");
System.out.println("4. Exit");
System.out.print("Please Enter your choice: ");
int choice = getUserInput();
if(choice == 1) {
logFeelings();
}
else if(choice == 2) {
viewLogs();
}
else if(choice == 3) {
viewEmotionalWellness();
}
else if(choice == 4) {
saveLogsToFile();//saves logs to json file
System.out.println("Program finished.");
System.out.println("\n--- Emotional Wellness Tracker ---");
break;//if user enters 4, program ends.
}else{
System.out.println("Invalid choice. Please Try again and input a valid option.");
}
}
}
/**
* function to Log Feelings from user
*/
public static void logFeelings() {
System.out.println("\n ---- Log your Feelings :) ---");//menu line output
System.out.print("Enter your Feelings: ");//menu line output
String feelings = sc.nextLine();//scanner stores the string of text user inputs on how they're feeling
int sentimentScore;
while(true) {
System.out.println("Rate your mood today (1-10, where 10 is the happiest level)");//menu line output
sentimentScore = getUserInput();//stores the sentimentScore that the user was feeling
if(sentimentScore>=1 && sentimentScore<=10) {//if the sentimentScore is between 1 and 10
break;//end the while loop
}
System.out.println("Invalid rating. Please enter a number between 1 and 10.");//else the program continues to ask for valid input
}
HashMap<String, String> logEntry = new HashMap<>();//Hashmap initialization
logEntry.put("log", feelings);
logEntry.put("logDate", java.time.LocalDate.now().toString());//stores the date of the log entry
logEntry.put("logTime", java.time.LocalTime.now().toString());//stores local time of feeling log
logEntry.put("sentimentScore",String.valueOf(sentimentScore));//stores the int to string value in the logEntry hashmap
logs.add(logEntry);
System.out.println("Log Feelings successfully added.");
}
/**
* function that views entries of Logs of users
*/
public static void viewLogs() {
if(logs.isEmpty()) {//if there are no log entries available
System.out.println("There are no log entries of feelings to view.");//menu line output
return;
}
System.out.println("\n ---Emotional Wellness Tracker ---");//menu line output
for(HashMap<String, String> logEntry : logs) {
System.out.println("Date: " + logEntry.get("logDate") + " |Mood: " + logEntry.get("sentimentScore"));//gets the date of the log entry and the sentimentScore the user input
System.out.println("Log of Feelings: " + logEntry.get("log"));//prints out the feeling input the user put at first
System.out.println("------------End of Log for the Date: " +logEntry.get("logDate") + " at the time of: "+logEntry.get("logTime") +"------------");
}
}
/**
* function to view a users emotional wellness, basically has multiple(8) functions within each(submenu) and a user can input numbers to select a specific
* emotion tracking.
*/
public static void viewEmotionalWellness() {
while(true){
//System sub menu options
System.out.println("\n ---Emotional Wellness Sub-Tracker ---");
System.out.println("Enter a number to view the sub-function listed");
System.out.println("1. View your most positive days");
System.out.println("2. View your most negative days");
System.out.println("3. View your total positive entries");
System.out.println("4.View your total negative entries");
System.out.println("5.View your average sentiment score");
System.out.println("6. View your highest mood improvement");
System.out.println("7.View your longest positive streak of days");
System.out.println("8.View your oldest entry in the log");
System.out.println("9. Exit");
System.out.print("Please Enter your choice: ");
int choice = getUserInput();//calls helper function to obtain input
//if else statements which call on sub-functions depending on user input.
if(choice == 1) {
List<HashMap<String, String>> results = mostPositiveDays();
for(HashMap<String, String> logEntry : results) {
System.out.println("\nDate: " + logEntry.get("logDate") +
" Time: " + logEntry.get("logTime") +
" | Positive Mood for that day: " + logEntry.get("sentimentScore") +
" | Feelings for that day: " + logEntry.get("log"));
}
}else if(choice == 2) {
List<HashMap<String,String>> results = mostNegativeDays();
for(HashMap<String, String> logEntry : results) {
System.out.println("\nDate: " + logEntry.get("logDate") +
" Time: " + logEntry.get("logTime") +
" | Negative Mood for that day: " + logEntry.get("sentimentScore") +
" | Feelings for that day: " + logEntry.get("log"));
}
}else if(choice == 3) {
totalPositiveEntries();
}else if(choice == 4) {
totalNegativeEntries();
}else if(choice == 5) {
averageSentimentScore();
}else if(choice == 6) {
highestMoodImprovement();
}else if(choice == 7) {
longestPositiveStreak();
}else if(choice == 8) {
oldestLogEntry();
}else if(choice == 9) {
break;
}
}
}
/**
* function to view a users emotional wellness, basically has multiple(8) functions within each(submenu) and a user can input numbers to select a specific
* emotion tracking.
*/
public static float averageSentimentScore() {
int numOfScores = logs.size();
float totalScores = 0;
//iterate over sentiment scores
for (HashMap<String, String> logEntry : logs) {
totalScores += Float.parseFloat(logEntry.get("sentimentScore"));
}
//find average
float avgScore = totalScores;
avgScore /= numOfScores;
return avgScore; //need to format
}
/**
* function to save the logged feelings from logFeelings() to the log.json file
*/
public static void saveLogsToFile() {
//create json array
JSONArray jsonlogs = new JSONArray();
//create json object for each hashmap
for (HashMap<String, String> logEntry : logs) {
JSONObject jsonLog = new JSONObject();
jsonLog.put("log", logEntry.get("log"));
jsonLog.put("logDate", logEntry.get("logDate"));
jsonLog.put("logTime", logEntry.get("logTime"));
jsonLog.put("sentimentScore", logEntry.get("sentimentScore"));
jsonlogs.put(jsonLog);
}
//write the json file
try (FileWriter file = new FileWriter(FILE_NAME)) {
file.write(jsonlogs.toString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* uses I/O to get previously saved Logs
*/
public static void loadLogsFromFile() {
//check if no file
File f = new File(FILE_NAME);
if (!(f.exists() && !f.isDirectory())) {
saveLogsToFile();
}
else {
//create new file
try (FileReader file = new FileReader(FILE_NAME)) {
BufferedReader reader = new BufferedReader(file);
//read file into string
String jsonString = "";
String line = reader.readLine();
while (line != null) {
jsonString += line;
line = reader.readLine();
}
reader.close();
//turn string into json array
JSONArray jsonlogs = new JSONArray(jsonString);
//create hashmaps for each json object
for (int i = 0; i < jsonlogs.length(); i++) {
HashMap<String, String> logEntry = new HashMap<>();
JSONObject jsonLog = jsonlogs.getJSONObject(i);
logEntry.put("log", jsonLog.getString("log"));
logEntry.put("logDate", jsonLog.getString("logDate"));
logEntry.put("logTime", jsonLog.getString("logTime"));
logEntry.put("sentimentScore", jsonLog.getString("sentimentScore"));
logs.add(logEntry); //add hasmap to logs array
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/** function to grab UserInput and avoid user inputting wrong data Type
* gives them a set number of valid attempts so there's no infinite loop
*
* @return returns the VALID choice the user inputs, if they get it within the max amount of attempts
*/
public static int getUserInput(){
int choice = -1;//def choice
int attempts = 0;
int MaxAttempts = 5;
while(attempts < MaxAttempts) {
try{
choice = sc.nextInt();//gets user input
sc.nextLine();//clears the buffer
return choice; //exit if input is invalid
}catch (InputMismatchException e){
System.out.println("Invalid input. Please try again.");
sc.nextLine();//Clears the invalid input
attempts++; //increments values
}
}
return -1;//returns -1 if input is invalid
}
/**
* function that sorts sentiment scores, and outputs the most positive days stored in the log (sentiment scores from 6-10)
* @return list of top 5 positive log entries
*/
public static List<HashMap<String, String>> mostPositiveDays() {
List<HashMap<String, String>> sortedLogs = new ArrayList<>(); // creates a new list for storing logs
// filters log entries from scores 6-10
for (HashMap<String, String> logEntry : logs) { // for every entry in logs
String scoreString = logEntry.get("sentimentScore"); // gets the sentiment score from the key
if (scoreString != null && !scoreString.isEmpty()) { // if that key does exist
int score = Integer.parseInt(scoreString); // parses the key(score) from string to int
if (score >= 6) { // if score is greater than or equal to 6
sortedLogs.add(logEntry); // add to sortedLogs
}
} else {
System.out.println("Sentiment score is empty. Please try again."); // if key does not exist
}
}
// sorting of orders for positive sentiment scores in descending order
// uses comparator inbuilt function
// uses lambda expression as log1 and log2 are elements of sortedLogs and compares them
// the order of log2 before log1 ensures that it is in descending (log1 before log2 = ascending)
sortedLogs.sort((log1, log2) -> Integer.compare(Integer.parseInt(log2.get("sentimentScore")), Integer.parseInt(log1.get("sentimentScore"))));
//returns sublist(a portion of the sortedLogs list(only the top 5)
return sortedLogs.subList(0, Math.min(5, sortedLogs.size())); // return top 5 entries
}
/**
* function that sorts sentiment scores, and outputs the most negative days stored in the log.(sentiment scores from 1-4)(5 being neutral)
* @return List of top 5 neg Log entries
*/
public static List<HashMap<String, String>> mostNegativeDays() {
List<HashMap<String, String>> sortedNegLogs = new ArrayList<>(); // creates a new list for storing logs
for (HashMap<String, String> logEntry : logs) { // for every entry in logs
String scoreString = logEntry.get("sentimentScore"); // gets the sentiment score from the key
if (scoreString != null && !scoreString.isEmpty()) { // if that key does exist
int score = Integer.parseInt(scoreString); // parses the key(score) from string to an int
if (score <= 4) { // if the score is less than or equal to 4
sortedNegLogs.add(logEntry); // adds to negativeLogs
}
} else {
System.out.println("Sentiment score is empty. Please try again."); // if key does not exist
}
}
// sorts new list of negative log entries in ascending order (starting with least happy day)
sortedNegLogs.sort(Comparator.comparingInt(log -> Integer.parseInt(log.get("sentimentScore"))));
//returns sublist(a portion of the sortedNegLogs list(only the top 5)
return sortedNegLogs.subList(0, Math.min(5, sortedNegLogs.size())); // return top 5 entries
}
public static void totalNegativeEntries(){}
public static void totalPositiveEntries(){}
public static void longestPositiveStreak(){}
public static void highestMoodImprovement(){}
public static void oldestLogEntry(){}
}