eCourses() { // Read data from "courses.txt" and initialize the ArrayList readCourseData(); } private void readCourseData() { try { File file = new File("cour
In Beginning Java, From my code, what exception can I create and where in my code?
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class ManageCourses {
private ArrayList<Course> courses = new ArrayList<>();
public ManageCourses() {
// Read data from "courses.txt" and initialize the ArrayList
readCourseData();
}
private void readCourseData() {
try {
File file = new File("courses.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(" ");
if (parts.length >= 3) {
String id = parts[0];
int units = Integer.parseInt(parts[1]);
String title = parts[2];
courses.add(new Course(id, units, title));
}
}
scanner.close();
} catch (FileNotFoundException e) {
System.err.println("Error: 'courses.txt' not found.");
}
}
public void listAllCourses() {
if (courses.isEmpty()) {
System.out.println("Your list is empty.");
} else {
for (Course course : courses) {
System.out.println(course);
}
}
}
public void addCourse(String id, int units, String title) {
courses.add(new Course(id, units, title));
}
public void searchCourseTitle(String target) {
if (target.isEmpty()) {
System.err.println("Error: Empty search word.");
return;
}
for (Course course : courses) {
if (course.getTitle().toLowerCase().contains(target.toLowerCase())) {
System.out.println(course);
}
}
}
public void searchCourseUnit(int unitValue) {
if (unitValue <= 0) {
System.err.println("Error: Invalid unit value.");
return;
}
for (Course course : courses) {
if (course.getUnits() >= unitValue) {
System.out.println(course);
}
}
}
public void saveCourseData() {
try {
PrintWriter writer = new PrintWriter("courses.txt");
for (Course course : courses) {
writer.println(course.getId() + " " + course.getUnits() + " " + course.getTitle());
}
writer.close();
} catch (FileNotFoundException e) {
System.err.println("Error: Unable to save data to 'courses.txt'");
}
}
}
Trending now
This is a popular solution!
Step by step
Solved in 3 steps