0

一个简单的数据文件,其中包含

1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N

每条线代表一个赛季的英超联赛,格式如下:年份、英超联赛、亚军、次要英超联赛、木勺、总决赛举行、获胜得分、失败得分、人群

我知道如何将数据存储到数组中并使用分隔符,但我不确定如何将每个数据项用逗号存储到单独的数组中?一些建议以及要使用的特定代码会很好。

更新:我刚刚添加了代码,但它仍然没有工作。这是代码:

    import java.io.*;
import java.util.Scanner;

public class GrandFinal {
    public static Scanner file;
    public static String[] array = new String[1000];

    public static void main(String[] args) throws FileNotFoundException {
        File myfile = new File("NRLdata.txt");
        file = new Scanner (myfile);
        Scanner s = file.useDelimiter(",");
        int i = 0;
        while (s.hasNext()) {
            i++;
            array[i] = s.next();
        }

        for(int j=0; j<array.length; j++) {
            if(array[j] == null)
                ;
            else if(array[j].contains("Y"))
                System.out.println(array[j] + " ");
        }
    }
}
4

2 回答 2

2

干得好。使用ArrayList. 它的动态方便

    BufferedReader br = null;
    ArrayList<String> al = new ArrayList();
    String line = "";

    try {

        br = new BufferedReader(new FileReader("NRLdata.txt"));

        while ((line = br.readLine()) != null) {
            al.add(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    for (int i = 0; i < al.size(); i++) {
        System.out.println(al.get(i));
    }

什么在你的情况下不起作用?

因为你的season数组是空的。您需要定义长度,例如:

private static String[] season = new String[5];

这是不对的,因为您不知道要存储多少行。这就是为什么我建议你使用ArrayList.

于 2013-05-30T08:28:53.253 回答
0

经过一番工作后,我想出了以下代码:

private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;

public static void main(String[] args) {
    try {
        file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
        counterReader = new BufferedReader(new FileReader(file));
        int numberOfLine = 0;
        String line = null;
        try {
            while ((line = counterReader.readLine()) != null) {
                numberOfLine++;
            }

            String[][] storeAnswer = new String[9][numberOfLine];
            int counter = 0;

            fileReader = new BufferedReader(new FileReader(file));

            while ((line = fileReader.readLine()) != null) {
                String[] temp = line.split(",");
                for (int j = 0; j < temp.length; j++) {
                    storeAnswer[j][counter] = temp[j];
                    System.out.println(storeAnswer[j][counter]);
                }
                counter++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    catch (FileNotFoundException e) {
        System.out.println("Unable to read file");
    }
}

我添加了counterReaderfileReader;用于计算行数,然后读取实际行数。storeAnswer二维数组包含您需要的信息。

我希望现在的答案更好。

于 2013-05-30T09:16:30.223 回答