Filtering & Aggregation over a CSV File

Question

I have a CSV File. The contents are like this:

 

Country,Player,Runs,ScoreRate,MatchDate,Weekday,Ground,Versus,URL

Afghanistan,Mohammad Shahzad,118,97.52,16-02-2010,Tue,Sharjah CA Stadium,Canada,../Matches/MatchScorecard_ODI.asp?MatchCode=3087

Afghanistan,Mohammad Shahzad,110,99.09,01-09-2009,Tue,VRA Ground,Netherlands,../Matches/MatchScorecard_ODI.asp?MatchCode=3008

Afghanistan,Mohammad Shahzad,100,138.88,16-08-2010,Mon,Cambusdoon New Ground,Scotland,../Matches/MatchScorecard_ODI.asp?MatchCode=3164

Afghanistan,Mohammad Shahzad,82,75.92,10-07-2010,Sat,Hazelaarweg,Netherlands,../Matches/MatchScorecard_ODI.asp?MatchCode=3153

 

I have to find the Total Scores by Afghanistan Player in the year 2010.

I wrote a code, but it shows an exception and outputs:

java.lang.NumberFormatException: For input string: ""

at java.lang.NumberFormatException.forInputString(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at A.main(A.java:38)

35135

However, the output should be 28 something.

Here is the code:

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class A {

public static void main(String args[]) throws FileNotFoundException

{

String csv="C:\\Users\\Dipayan\\Desktop\\odi-batting.csv";

  BufferedReader br=new BufferedReader(new FileReader(csv));

String line=" ";

int sum=0;

int count=0;

int []a=new int[10000];

try {

br.readLine();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

while((line=br.readLine())!=null)

{

String [] f= line.split(",");

if((f[4]="2010")!= null)

{

a[count]=Integer.parseInt(f[2]);

sum=sum+a[count];

count++;

}

}

} catch (NumberFormatException | IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(sum);

}

}

 

Answer

It’s awkward to perform structured computations directly in Java. Here we handle your question in SPL (Structured Process Language):

A

1

=file("data.csv").import@t   (;,",")

2

=A1.sum(if(Country=="Afghanistan"&&

year(datetime(MatchDate,"dd-MM-yyyy"))==2010,ScoreRate))

A1: Read the CSV file;

A2: Sum ScoreRate by the specified condition.

To call an SPL script in a Java application, see How to Call an SPL Script in Java.