java - 向二维数组添加元素有困难

标签 java arrays

我有一个如下所示的 .txt 文件:

Mathematics:MTH105
Science:SCI205
Computer Science:CPS301
...

我有一个作业,要求我读取文件并将每一行放入一个数组中,该数组应如下所示:

subjectsArray[][] = {
   {"Mathematics", "MTH105"},
   {"Science", "SCI205"},
   {"Computer Science", "CPS301"}
};

当我尝试将文件的内容添加到二维数组时,出现编译错误:

private static String[][] getFileContents(File file) {

    Scanner scanner = null;
    ArrayList<String[][]> subjectsArray = new ArrayList<String[][]>();

    //Place the contents of the file in an array and return the array
    try {
        scanner = new Scanner(file);
        int i = 0;

        while(scanner.hasNextLine()) {

            String line = scanner.nextLine();
            String[] lineSplit = line.split(":");

            for(int j = 0; j < lineSplit.length; j++) {
                subjectsArray[i][j].add(lineSplit[0]); //The type of the expression must be an array type but it resolved to ArrayList<String[][]>
            }

            i++;
        }
        return subjectsArray;

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        scanner.close();
    }
    return null;
}

错误读取:

The type of the expression must be an array type but it resolved to ArrayList<String[][]>

我是多维数组的新手,不确定我做错了什么。有人可以告诉我我做错了什么吗?

最佳答案

您的第一个错误是选择结果类型:此类型

ArrayList<String[][]>

表示三维结构——二维数组的列表。你需要的是一个二维结构,例如

ArrayList<String[]>

所以第一个修复是这样的:

List<String[]> subjectsArray = new ArrayList<String[]>(); // Note the type on the left: it's an interface

完成此操作后,其余代码将自行流动:您不需要内部 for循环,它被一行替换:

subjectsArray.add(lineSplit);

最终修复是return行:您需要转换 List<String[]>String[][] ,可以通过调用 toArray() 来完成,像这样:

return subjectsArray.toArray(new String[subjectsArray.size()][]);

关于java - 向二维数组添加元素有困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23717653/

相关文章:

java - 使用值对象中的字段对 map 列表进行排序

java - 简单参数的堆污染

java - 如何逐个下载多个pdf文件

javascript - js - 循环多维数组

C++ 不需要返回值

arrays - 检查元素是否存在于 Bash 数组中

uitableview - 如何从 NSMutableArray 在 UITableViewCell 中显示图像?

java - Zxing 二维码扫描仪自动关闭冲洗灯

java - 对于线程脚本,在 Groovy 中使用同步 println 和仅使用 println 有什么区别?

c - 在 C 中快速打印字符串或数组的字符