-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiscussionBoard.java
More file actions
341 lines (294 loc) · 12.1 KB
/
Copy pathDiscussionBoard.java
File metadata and controls
341 lines (294 loc) · 12.1 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
335
336
337
338
339
340
341
//Aly Sibak
//1276226
//to compile:
//cd lab3
//javac User.java Post.java TextPost.java PollPost.java DiscussionBoard.java
//to run:
//java discussionboard cis2430
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class DiscussionBoard {
private ArrayList<User> users = new ArrayList<>();
private ArrayList<Post> posts = new ArrayList<>();
// Method to ensure input is not blank
private String getNonBlankInput(Scanner scanner, String prompt) {
String input;
do {
System.out.println(prompt);
input = scanner.nextLine().trim();
if (input.isBlank()) {
System.out.println("Input cannot be blank. Please try again.");
}
} while (input.isBlank());
return input;
}
// Create a new user
public void createUser(Scanner scanner) {
String fullName = getNonBlankInput(scanner, "Enter full name:");
System.out.println("Enter username (optional):");
String username = scanner.nextLine().trim();
if (username.isBlank()) {
username = fullName.split(" ")[0].toLowerCase();
}
for (User user : users) {
if (user.getUsername().equalsIgnoreCase(username)) {
System.out.println("Error: Username already exists.");
return;
}
}
User newUser = new User(fullName, username);
users.add(newUser);
System.out.println("User created successfully.");
}
// Code to create a new post, either text or poll
public void createPost(Scanner scanner) {
String username = getNonBlankInput(scanner, "Enter username:").toLowerCase();
User user = null;
for (User u : users) {
if (u.getUsername().equals(username)) {
user = u;
break;
}
}
if (user == null) {
System.out.println("Error: User not registered.");
return;
}
String postType;
do {
postType = getNonBlankInput(scanner, "Enter the post type ('text', 'poll'):");
if (!postType.equalsIgnoreCase("text") && !postType.equalsIgnoreCase("poll")) {
System.out.println("Invalid post type. Please enter 'text' or 'poll'.");
}
} while (!postType.equalsIgnoreCase("text") && !postType.equalsIgnoreCase("poll"));
String title = getNonBlankInput(scanner, "Enter title:");
if (postType.equalsIgnoreCase("text")) {
String content = getNonBlankInput(scanner, "Enter content:");
TextPost newPost = new TextPost(title, content, user);
posts.add(newPost);
System.out.println("Text post created successfully by user: " + user.getUsername());
} else if (postType.equalsIgnoreCase("poll")) {
String options = getNonBlankInput(scanner, "Enter poll options separated by semicolons:");
PollPost newPost = new PollPost(title, options, user);
posts.add(newPost);
System.out.println("Poll post created successfully by user: " + user.getUsername());
}
}
// View all posts that have been created or not created yet
public void viewAllPosts() {
if (posts.isEmpty()) {
System.out.println("No posts available.");
} else {
for (Post post : posts) {
post.display();
}
}
}
// Vote in a poll
// Vote in a poll
public void voteInPoll(Scanner scanner) {
String input = getNonBlankInput(scanner, "Enter the post ID to vote in:");
// Declare postId
int postId;
// Check if the input is a valid number
try {
postId = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Invalid input: Post ID must be a number.");
return;
}
// Adjust postId to match the list index (subtract 1 for zero-based index)
if (postId < 1 || postId > posts.size()) {
System.out.println("Error: Invalid post ID.");
return;
}
Post post = posts.get(postId - 1); // Subtract 1 for zero-based indexing
if (!(post instanceof PollPost)) {
System.out.println("Error: Post not found or not a poll.");
return;
}
PollPost pollPost = (PollPost) post;
String[] options = pollPost.getOptions();
for (int i = 0; i < options.length; i++) {
System.out.println((i + 1) + ") " + options[i]);
}
int choice = Integer.parseInt(getNonBlankInput(scanner, "Enter your choice:")) - 1;
if (choice < 0 || choice >= options.length) {
System.out.println("Invalid choice.");
} else {
pollPost.vote(choice);
System.out.println("Vote cast successfully.");
}
}
// Save discussion board to file
public void saveToFile(String filename) throws IOException {
try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
for (Post post : posts) {
if (post instanceof TextPost) {
writer.println("TEXT|" + post.getId() + "|" + post.getUser().getUsername() + "|" + post.getTitle()
+ "|" + ((TextPost) post).getContent());
} else if (post instanceof PollPost) {
writer.println("POLL|" + post.getId() + "|" + post.getUser().getUsername() + "|" + post.getTitle()
+ "|" + String.join(";", ((PollPost) post).getOptions()));
}
}
}
}
// Load discussion board from file
public void loadFromFile(String filename) throws IOException {
File file = new File(filename);
if (!file.exists()) {
System.out.println("File not found, starting with blank discussion board.");
return;
}
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("\\|");
// Check if the line has the minimum number of parts (for post data)
if (parts.length < 3) {
System.out.println("Error: Invalid line format, skipping: " + line);
continue;
}
String recordType = parts[0];
if (recordType.equals("USER")) {
// Check if there are enough parts for a user
if (parts.length < 3) {
System.out.println("Error: Invalid user format, skipping: " + line);
continue;
}
String username = parts[1];
String fullName = parts[2];
users.add(new User(fullName, username));
} else {
String username = parts[2];
User user = null;
// Try to find the user by username
for (User u : users) {
if (u.getUsername().equals(username)) {
user = u;
break;
}
}
// If user is not found, auto-create the user
if (user == null) {
System.out.println("Auto-creating user for post: " + username);
user = new User(username, username); // Placeholder for full name
users.add(user);
}
// Handle text posts
if (recordType.equals("TEXT") && parts.length >= 5) {
TextPost post = new TextPost(parts[3], parts[4], user);
posts.add(post);
}
// Handle poll posts
else if (recordType.equals("POLL") && parts.length >= 5) {
PollPost post = new PollPost(parts[3], parts[4], user);
posts.add(post);
}
// Handle invalid post format
else {
System.out.println("Error: Invalid post format, skipping: " + line);
}
}
}
}
}
// View posts by username
public void viewPostsByUsername(Scanner scanner) {
String username = getNonBlankInput(scanner, "Enter username:").toLowerCase();
boolean found = false;
for (Post post : posts) {
if (post.getUser().getUsername().equalsIgnoreCase(username)) {
post.display();
found = true;
}
}
if (!found) {
System.out.println("No posts found for the given username.");
}
}
// View posts by keyword, matching word-by-word and ignoring case
public void viewPostsByKeyword(Scanner scanner) {
String keyword = getNonBlankInput(scanner, "Enter keyword:").toLowerCase();
boolean found = false;
for (Post post : posts) {
// Tokenize the title into words
String[] titleWords = post.getTitle().toLowerCase().split("\\s+");
// Check if any of the words in the title matches the keyword
for (String word : titleWords) {
if (word.equals(keyword)) {
post.display();
found = true;
break; // Stop checking this post once a match is found
}
}
}
if (!found) {
System.out.println("No posts found containing the exact keyword.");
}
}
// Main menu
public void menu(String filename) throws IOException {
Scanner scanner = new Scanner(System.in);
// Try to load the discussion board from the file
loadFromFile(filename);
while (true) {
System.out.println("1) Create new user");
System.out.println("2) Create new post");
System.out.println("3) View all posts");
System.out.println("4) Vote in poll");
System.out.println("5) View all posts with a given username");
System.out.println("6) View all posts with a given keyword");
System.out.println("7) Save Discussion Board");
System.out.println("8) End Program");
if (scanner.hasNextInt()) {
int choice = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
switch (choice) {
case 1:
createUser(scanner);
break;
case 2:
createPost(scanner);
break;
case 3:
viewAllPosts();
break;
case 4:
voteInPoll(scanner);
break;
case 5:
viewPostsByUsername(scanner);
break;
case 6:
viewPostsByKeyword(scanner);
break;
case 7:
saveToFile(filename);
System.out.println("Discussion board saved successfully.");
break;
case 8:
System.out.println("Program Ended.");
return; // Exit the loop and program
default:
System.out.println("Invalid option.");
}
} else {
System.out.println("Invalid input. Please enter a number between 1 and 8.");
scanner.next(); // Consume the invalid input
}
}
}
// Main method to start the program
public static void main(String[] args) throws IOException {
DiscussionBoard db = new DiscussionBoard();
// Check if a file was provided as a command-line argument
if (args.length > 0) {
db.menu("./boards/" + args[0] + ".dboard");
} else {
db.menu("./boards/blank.dboard"); // Default to a blank discussion board
}
}
}