0% found this document useful (0 votes)
11 views2 pages

Student Marks Average Calculator

The document contains a Java program that processes student data from input files, calculates average marks, and writes the results to output files. It defines a Student class to hold student information and a FileProcessor class to handle file reading and writing in a multi-threaded manner. The main method initializes sample student data, writes it to files, and starts threads to process each file concurrently.

Uploaded by

MAD MAX
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Student Marks Average Calculator

The document contains a Java program that processes student data from input files, calculates average marks, and writes the results to output files. It defines a Student class to hold student information and a FileProcessor class to handle file reading and writing in a multi-threaded manner. The main method initializes sample student data, writes it to files, and starts threads to process each file concurrently.

Uploaded by

MAD MAX
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

*; public void run() {


import [Link].*; List<Student> students = new
ArrayList<>();
class Student {
private String name; try {
private String rollNumber; // Reading the file and populating the
private int[] marks = new int[3]; // Marks 1, students list
2, and 3 synchronized (lock) {
try (BufferedReader reader = new
public Student(String name, String BufferedReader(new FileReader(inputFile))) {
rollNumber, int marks1, int marks2, int String line;
marks3) { while ((line = [Link]()) !=
[Link] = name; null) {
[Link] = rollNumber; String[] parts = [Link](",");
[Link][0] = marks1; if ([Link] == 5) { // 1
[Link][1] = marks2; name, 1 rollNumber, 3 marks
[Link][2] = marks3; String name = parts[0].trim();
} String rollNumber =
parts[1].trim();
public int[] getMarks() { int marks1 =
return marks; [Link](parts[2].trim());
} int marks2 =
[Link](parts[3].trim());
public double getAverageMarks() { int marks3 =
return (marks[0] + marks[1] + marks[2]) / [Link](parts[4].trim());
3.0; [Link](new
} Student(name, rollNumber, marks1, marks2,
marks3));
@Override }
public String toString() { }
return "Student{" + }
"name='" + name + '\'' + }
", rollNumber='" + rollNumber + '\'' +
", marks=" + [Link](marks) + // Calculate total marks and average
'}'; double totalMarks = 0;
} for (Student student : students) {
} totalMarks +=
[Link]();
class FileProcessor implements Runnable { }
private final String inputFile;
private final String outputFile; double averageMarks =
private static final Object lock = new [Link]() ? 0 : totalMarks /
Object(); [Link]();

public FileProcessor(String inputFile, String // Write the average to the


outputFile) { corresponding output file
[Link] = inputFile; synchronized (lock) {
[Link] = outputFile; try (BufferedWriter writer = new
} BufferedWriter(new FileWriter(outputFile))) {
[Link]("Average Marks: " +
@Override averageMarks);
} }
}
// Create and start a thread for each
[Link]("Processed file: " + input-output file pair
inputFile + " | Average Marks: " + List<Thread> threads = new ArrayList<>();
averageMarks); for (int i = 0; i < [Link]; i++) {
Thread processor = new Thread(new
} catch (IOException e) { FileProcessor(inputFiles[i], outputFiles[i]));
[Link]("Error processing file [Link]();
" + inputFile + ": " + [Link]()); [Link](processor);
} }
}
} // Wait for all threads to finish
try {
public class File { for (Thread thread : threads) {
public static void main(String[] args) { [Link]();
// List of student files and their }
corresponding output files } catch (InterruptedException e) {
String[] inputFiles = {"[Link]", [Link]("Thread interrupted:
"[Link]", "[Link]"}; " + [Link]());
String[] outputFiles = {"[Link]", }
"[Link]", "[Link]"};
[Link]("All files processed.
String[][] data = { Check individual output files for results.");
{"John Doe", "R123", "85", "90", "88"}, }
{"Jane Smith", "R124", "78", "82", }
"80"},
{"Alice Brown", "R125", "92", "88",
"91"},
{"Bob White", "R126", "70", "75", "68"},
{"Charlie Black", "R127", "88", "92",
"85"}
};

// List of student files to write


String[] files = {"[Link]",
"[Link]", "[Link]"};

// Write sample data into each file


for (String file : files) {
try (BufferedWriter writer = new
BufferedWriter(new FileWriter(file))) {
for (String[] studentData : data) {
[Link]([Link](", ",
studentData));
[Link]();
}
} catch (IOException e) {
[Link]("Error writing to
file " + file + ": " + [Link]());
}

Common questions

Powered by AI

The main method in the File class orchestrates the student data processing by initializing input and output file arrays, creating threads for file processing, and starting each thread. It uses a loop to associate each input file with a corresponding output file through a separate FileProcessor instance, and adds these to a list of threads. After starting the threads, it then waits for all threads to complete using the join method, ensuring that the program execution continues only after all files are processed. This method effectively coordinates the concurrent file processing tasks .

Using multiple threads in the FileProcessor class allows for parallel processing of input files, which can significantly improve performance on systems with multiple CPU cores. Each thread handles a separate input-output file pair, allowing tasks to be performed concurrently rather than sequentially. However, this concurrency introduces risks such as potential race conditions, where threads might interfere with each other if they access shared resources unsafely. Proper synchronization is required to mitigate these risks .

Changing the number and order of input-output files in the File class can directly impact processing results and output, as each FileProcessor is paired with a specific input-output file pair. If the files do not match the expected order, outputs might contain incorrect data as threads will process unintended pairs. Moreover, reducing or increasing the number of files changes the total data processed and the number of threads spawned, affecting performance and the distribution of tasks. Ensuring correct file order and count is essential for desired processing results .

Removing the synchronized blocks from the FileProcessor would significantly impact performance by introducing the risk of race conditions and data corruption. With no synchronization, multiple threads could simultaneously access and modify shared resources—such as input and output files—leading to unpredictable and erroneous output, especially when reading and writing to files concurrently. The absence of these blocks would compromise the integrity of data processing and output results .

The Student class calculates the average marks by summing the three elements in the marks array and then dividing by 3.0 to ensure a double result. If the array had four elements, the method would need to be adjusted to sum all four elements and divide by 4.0 to maintain an accurate average calculation. Otherwise, the method would result in an incorrect average if it only accounted for three marks while the array contained four .

The FileProcessor class manages exceptions using try-catch blocks that capture IOException during file reading and writing. It logs errors by printing a message to the standard error stream. While this approach effectively prevents the application from crashing due to I/O errors, it provides limited flexibility for error recovery or handling specific error types differently. The current implementation simply reports errors without retrying operations or implementing alternative fallbacks, which could be a drawback in more robust error management strategies .

The Student class, designed with encapsulation in mind by using private fields and public methods, positively impacts the program's scalability and maintainability. Its constructor initializes the student details, and methods like getMarks and getAverageMarks facilitate accessing marks and calculating averages without directly exposing internal data structures. This separation of concerns makes the class extensible, for instance, by easily adding new attributes or methods without significant changes to existing functionality. Its design adheres to good object-oriented principles, making the codebase easier to understand and modify .

The synchronized block in the FileProcessor class ensures that threads access shared resources, specifically file operations, in a thread-safe manner. This prevents concurrent threads from attempting to read and write files simultaneously, which could potentially lead to inconsistent data or corrupted files. The synchronized block is crucial for maintaining data integrity while reading student data and writing average marks to the output files .

The relationship in the FileProcessor class represents I/O-bound operations where the time spent processing is largely due to reading from and writing to files. I/O-bound operations are typically slower compared to CPU-bound tasks. In a multithreaded context, such as the one used here, the program can perform other tasks like CPU computations or handle multiple files at once while waiting for I/O operations to complete. This design can effectively hide latency, improving overall throughput and performance when dealing with large volumes of data .

The use of a static lock object in the FileProcessor class ensures that all threads created from this class access shared resources in a controlled manner, preventing simultaneous writes and reads. While this approach is effective, it serially limits access to critical sections, potentially reducing overall throughput if many threads compete for the lock. An alternative might be to employ finer-grained locking mechanisms, like separately synchronizing read and write operations if they do not conflict, or using java.util.concurrent utilities such as ReentrantLock to potentially improve concurrency and efficiency .

You might also like