【发布时间】:2023-04-03 20:14:01
【问题描述】:
class Result {
public static int diagonalDifference(List<List<Integer>> arr) {
int sum_a = 0;
int sum_b = 0;
int sum_c = 0;
int n = 3;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++,i++){
sum_a += arr[i][j];
}
}
for(int i = 0; i < n ; i++){
for(int j = n-1; j >= 0; j--,i++){
sum_b += arr[i][j];
}
}
return sum_c = sum_a + sum_b;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<List<Integer>> arr = new ArrayList<>();
IntStream.range(0, n).forEach(i -> {
try {
arr.add(
Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList())
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
int result = Result.diagonalDifference(arr);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
**我使用了两个整数变量来添加数组的对角线和。我得到一个编译时错误。 Solution.java:38:错误:需要数组,但找到了 List> sum_a += arr[i][j];
Solution.java:45:错误:需要数组,但找到 List> sum_b += arr[i][j]; 谁能帮我解决这个问题。**
【问题讨论】:
-
你不使用方括号来访问列表的元素,你使用'get'方法:
arr.get(i).get(j)
标签: java arrays list data-structures