简体   繁体   English

读取CSV文件并使用Java组织数据

[英]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. 我正在尝试编写一个从名为matchs.csv的csv文件读取的Java程序。 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. 一场足球比赛可以以赢球或平局结束:在第一种情况下,获胜者队获得3分,在失败者中无人获得点数;在第二种情况下,两支球队中的每支获得1分。

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. 这意味着比赛在17/08/2013进行,阿森纳进1球,阿斯顿维拉3球:阿森纳得到0分,阿斯顿维拉3分。

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. 首先,您的输入必须是可解析的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 代替您的System.out.println使用类似

parseLine(data);

ParseLine would read the line and break it into pieces. ParseLine会读取该行并将其分成几部分。 I suggest you use the split(",") function to get the pieces you want, then just reference them by index. 我建议您使用split(“,”)函数获取所需的片段,然后按索引引用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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