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'