0

我正在寻找一种将制表符分隔的棒球统计文件读入二维数组列表的方法。我正在使用扫描仪读取文件,但我想不出如何将一行读入数组列表,在换行处停止,然后将下一行读入下一个数组列表。

这是我第一次尝试创建多维数组列表,我认为这与读取多维数组大致相同。我显然错了。

    public static ArrayList dataRead(String fileloc) throws FileNotFoundException {
    ArrayList array = new ArrayList<ArrayList>();
    Scanner s = new Scanner(new File(fileloc)).useDelimiter("\t");
    ArrayList<String> rows = new ArrayList<String>();
    ArrayList cols = new ArrayList();
    while(s.nextLine() != null) {
        cols.add(s.next());
    }
    return array;
}

这是我现在的代码。将每一行读入一个字符串,由返回分隔,然后将每个字符串读入一个适当的数组列表,这是一个更好的选择吗?

4

3 回答 3

4

您可以使用opencsv并将分隔符设置为制表符。查看我提供的链接上的示例。

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '\t');
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    // nextLine[] is an array of values from the line
    System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

尽管从您的问题中不清楚您在尝试“自己动手”时的实际问题是什么

于 2012-04-04T18:25:59.220 回答
1

I'm not sure what the stats look like, but it might be better to use a HashMap which has Key/value pairs instead, but I could be wrong. I don't know what your dataset looks like.

For a start, you can delimit the lines by using the "\t" escape character. For Example:

Scanner s = new Scanner(input).useDelimiter("\t");

Then you can loop through the results and for every pair add it to the map.

于 2012-04-04T18:30:14.823 回答
1

我认为您需要重新考虑您的数据结构,使其更有利于您尝试存储的内容。我建议您创建一个播放器对象并将其存储到数组列表中。

public class Player{
    double battavg;
    String name;
    //add more values like rbi, etc.
    public Player(name,battavg){
        this.name=name;
        this.battavg=battavg;
    }
    public String getName(){
        return name;
    }
    public String getBattAvg(){
        return battavg;
    }
    public setBattAvg(double battavg){
        this.battavg=battavg;
    }
    public setName(String name){
        this.name=name;
    }
}

public class baseball{
    public static void main(String[] args){
        ArrayList<Player> list = new ArrayList<Player>();
        //read in values from csv
        list.add(new Player(name,battavg));
    }
}
于 2012-04-04T18:47:10.527 回答