public static void main(String[] args) {
List<List<Integer>> arr = new ArrayList<>();
for(int i = 0; i < 3; i++ ){
arr.add(new ArrayList<Integer>());
arr.get(i).add(i + ( (int) Math.random() * 100));
}
for(List<Integer> intrArr : arr){
System.out.println("");
for(Integer integer : intrArr){
System.out.print(integer);
}
}
diagonalDifference(arr);
}
public static int diagonalDifference(List<List<Integer>> arr) {
int intDiagonalDifference = 0;
int primaryDiagonal = 0;
int seconadaryDiagonal = 0;
for(int i = 0; i < arr.size(); i++ ){
primaryDiagonal += arr.get(i).get(i);
seconadaryDiagonal += arr.get(i).get(arr.size() - i);
}
intDiagonalDifference = Math.abs(primaryDiagonal - seconadaryDiagonal);
return intDiagonalDifference;
}
Вывод:
0
1
2Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:458)
at main.hackerRank.diagonalDifference(hackerRank.java:32)
at main.hackerRank.main(hackerRank.java:22)
Process finished with exit code 1
Задача создать матрицу типа
1 3 9
5 6 7
0 8 7
И найти ее DiagonalDifference с помощью вложенного arrayList