我有一个如下所示的 .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/