Skip to content

Instantly share code, notes, and snippets.

@n2o
Last active May 18, 2017 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n2o/7b8789e361203c5104ddf5b0b0f78143 to your computer and use it in GitHub Desktop.
Save n2o/7b8789e361203c5104ddf5b0b0f78143 to your computer and use it in GitHub Desktop.
Professional Programming: Results of practical exercises, week 4

Task: Read a CSV file and correctly parse it. Then calculate the sum of those students, who achieved 50 points or more in the exam.

The CSV file is located in resources/punkte.csv.

App.java

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import java.io.FileReader;
import java.io.Reader;

public class App {
    private static Iterable<CSVRecord> parseCSV() {
        try {
            Reader csvReader = new FileReader("resources/punkte.csv");
            return CSVFormat.DEFAULT
                    .withFirstRecordAsHeader()
                    .withDelimiter(';')
                    .parse(csvReader);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static int passedExam(Iterable<CSVRecord> records) {
        int sum = 0;
        float points;
        for (CSVRecord record : records) {
            if (!record.get("klausur").isEmpty()) {
                points = Float.parseFloat(record.get("summe-klausur-punkte"));
                if (points >= 50) {
                    sum++;
                }
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        Iterable<CSVRecord> records = parseCSV();
        System.out.println(passedExam(records));
    }
}

Additional Gradle dependencies:

compile 'org.apache.commons:commons-csv:1.4'

Or with streams:

private static int passedExamsStream(Iterable<CSVRecord> records) {
    return (int) Streams.stream(records)
            .filter(record -> !record.get("klausur").isEmpty())
            .filter(record -> Float.parseFloat(record.get("summe-klausur-punkte")) >= 50)
            .count();
}

For this, you need the Google common library guava:

compile 'com.google.guava:guava:21.0'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment