'How do I manipulate a CSV file?

Create a program in Java that will read the CSV file and compute the Final Grade of the student using the computation below: Lab Exercise * 30% + Long Quiz * 30% + Alternative Assessment * 40% = Final Grade Then, display the final grade of each student.

We will be using the java.io package and so far this is what I come up with

import java.io.*;
public class ReadingFile {
public static void main (String[]args){

    try{

        File myFile = new File("Grades.csv");
        BufferedReader br = new BufferedReader(new FileReader(myFile));
        String allLines = "";

        while((allLines = br.readLine()) != null){
            String row [] = allLines.split(",");
            double finalGrade = (Double.parseDouble(row[1])*.30) + (Double.parseDouble(row[2])*.30) + (Double.parseDouble(row[3])*.40);

        }

    }
    catch(IOException err){
        System.err.println("File not found.");
        
    }
}
}

I know that there are a lot of missing code but this is all what I can do with the best of my knowledge and abilities.



Solution 1:[1]

Assume your content of Grades.csv is as below

35,91,24
53,63,73
13,23,33

Some tips

  1. Use try-with-resources statement to ensure that BufferedReader is closed at the end of the statement.

  2. Java uses zero-based indexing, so you should use row[0] to read the first score.

  3. Use a logger or e.printStackTrace() to help you debugging.

public static void main(String[] args) {
    try (BufferedReader br = new BufferedReader(new FileReader(new File("Grades.csv")))) {
        String allLines;
        while ((allLines = br.readLine()) != null) {
            String[] row = allLines.split(",");
            double finalGrade =
                (Double.parseDouble(row[0]) * .30) + (Double.parseDouble(row[1]) * .30) + (Double.parseDouble(row[2]) * .40);
            System.out.println(finalGrade);
        }
    } catch (IOException e) {
        System.err.println("some error message");
        e.printStackTrace();
    }
}

The output will be

47.4
64.0
24.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1