简体   繁体   中英

Read CSV files and organising the data in Java

I was wondering anyone one can help me please?

I am trying to write a java program that read from a csv file called matches.csv. A single football match can end with a win or a draw: in first case the winner team get 3 points and the loser none, in the second case of draw each of the two teams get 1 point.

In the file it contains the following data.

17/08/2013 Arsenal Aston Villa 1 3
24/08/2013 Aston Villa Liverpool 0 1

This means that a match has been played on the 17/08/2013 where Arsenal scored 1 goal while Aston Villa 3 goals: thus Arsenal got 0 points while Aston Villa 3 points.

How can I structure my output to make it make it read

Position Team Played Points
1 Aston Villa 2 3
2 Liverpool 1 3
3 Arsenal 1 0 

Here is my current attempt.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Teams
{

    public static void main(String[] args)
    {
        String fileName = "matches.csv";
        File file = new File(fileName);

        try
        {
            Scanner inputStream = new Scanner(file);
            while (inputStream.hasNext())
            {
                String data = inputStream.next();
                System.out.println(data);
            }
        }  
        catch(FileNotFoundException e)
        {
            e.printStackTrace();
        }

   }

}

First, your input has to be a parseable CSV. So, use commas.

Supposing the file had commas, it would be something like

dateddmmyyyy,team1name,team2name,team1score,team2score
17/08/2013,Arsenal,Aston Villa,1,3
24/08/2013,Aston Villa,Liverpool,0,1

Then you can use the file you pasted here. Instead of your System.out.println, use something like

parseLine(data);

ParseLine would read the line and break it into pieces. I suggest you use the split(",") function to get the pieces you want, then just reference them by index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM