/** * "On the fly"-code of the first exercise on * 30/04/2009 (augmented with some comments). * * Compile with: * javac Homework.java * Run with: * java Homework */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class Homework { // delimiter of our comma separated file public static String delim = ","; public static void main(String args[]) { /* we don't care about errors and wrap * the whole code into a try-catch block */ try { /* Create a bufferedReader and initialized it with * the first argument given on the commandline * as filename. The bufferedReader allows linewise * reading of the file. */ FileReader fi = new FileReader(new File(args[0])); BufferedReader br = new BufferedReader(fi); /* variable to hold the current line, while we read the * file linewise. */ String line = null; // Tokenizer to get the values separated by the delimiter. StringTokenizer strToken = null; /* StudentName (first column) and * Points (second column) */ String studentName = null; int points = 0; /* variable to calculate intermediate values, while we * aggregate the point data. */ int interm = 0; /* Key-ordered Map datastructure, to hold the current data, we are * calculating. * A Map is a structure which maps key-values to data. * For example: * {studentName1 -> 1, studentName2 -> 5, ..., studentNameN -> 10} * * Since the TreeMap is ordered after key values, we don't care about * sorting in the end. */ Map studentPoints = new TreeMap(); // read the file linewise while ((line = br.readLine()) != null) { strToken = new StringTokenizer(line, delim); // get the data of interest (first and last column) studentName = strToken.nextToken(); strToken.nextElement(); points = Integer.parseInt(strToken.nextToken()); // calculation of the total sum if (studentPoints.containsKey(studentName)) { interm = studentPoints.get(studentName).intValue(); studentPoints.put(studentName, new Integer(interm + points)); } else { studentPoints.put(studentName, new Integer(points)); } } /* print out the result */ for (String student : studentPoints.keySet()) { System.out.println(student + " -> " + studentPoints.get(student).toString()); } } catch (Exception exc) { // exception handling exc.printStackTrace(); } } }