【问题标题】:Putting unordered items into an array from a file将文件中的无序项放入数组中
【发布时间】:2016-04-13 19:22:48
【问题描述】:

我有三个 CSV 文件,其中的数据由一串数字链接,我创建了一个二维数组来将所有数据存储在一起,并且有一个 csv 文件,其他文件中的数据不在相同的顺序,所以我不能简单地将文件的第 1 行读入数组的第一行。

这是我的代码

public class grades {
public static void main(String[] args) throws FileNotFoundException 
{
    int rowc = 0;
    String inputLine = "";

    String[][] students = new String[10][6];
    //Get scanner instance
    Scanner scanner = new Scanner(new File("/IRStudents.csv"));

    //Set the delimiter used in file
    scanner.useDelimiter(",");

    while (scanner.hasNextLine()) {
        inputLine = scanner.nextLine();
        String [] line = inputLine.split(",");

        for (int x = 0; x < 2; x++) {
            students[rowc][x] = line[x];
        }
        if (rowc < 9) {
            rowc++;
        }
        else {
            break;
        }
    }
    System.out.println(Arrays.deepToString(students));
    scanner.close();
    Scanner input = new Scanner(new File("/IR101.csv"));
    input.useDelimiter(",");
    while (input.hasNext()) {
        inputLine = input.nextLine();
        String[] line = inputLine.split(",");
        for (int i = 0; i < 1; i++) {
            System.out.println(line[0]);
            System.out.println(students[0][i]);
            if (line[0].equals(students[0][i])) {
                students[2][i] = line[0];
            }
        }
    }
    System.out.println(Arrays.deepToString(students));

}
}

我知道其中很多不是很整洁或高效,但我宁愿它工作正常。无论如何,我将如何遍历文件并将每个项目添加到数组的第 3 列,其中相应的字符串是链接它们的位置?

谢谢。

【问题讨论】:

  • 你应该使用 csv 阅读器,而不是扫描仪会让你的代码看起来更干净。

标签: java arrays csv


【解决方案1】:

希望我能正确理解您的问题。

在您的情况下,您可以将第三个 csv 加载到内存中,然后遍历数组(一个 for 在另一个 for 中)并检查一个数组的键匹配另一个上的键(链接它们的字符串)并绑定它们。

提示:您可以像这样初始化学生属性:

students[rowc] = line;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多