Вот мой код, цель которого - написать программу, которая случайным образом вводит 20 чисел от 1 до 10 в двумерный массив из 5 строк и 4 столбцов. Программа должна вывести двумерный массив, а также сумму каждой строки и сумму каждого столбца. Я не могу понять, где я получаю это исключение (вот мой общий вывод):
Project 3...
2D Array elements: 6, 6, 7, 10, 4, 4, 0, 9, 0, 1, 3, 10, 1, 10, 10, 9, 10, 5, 8, 2,
Sum of Rows: 115
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at arrayProject.projectthree(arrayProject.java:96)
at arrayProject.main(arrayProject.java:19)
Вот мой код:
public static void projectthree(){
System.out.println("Project 3...");
/*Write a program that randomly inputs 20 numbers from 1 to 10 into a 2-D array of 5 rows and 4 columns.
The program should output the 2-D array, the sum of each row storing numbers in a parallel array and
the sum of each column storing numbers in a parallel array*/
int array[][] = new int[5][4];
Random randomizer = new Random();
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
array[i][j] = randomizer.nextInt(11); //Assign random values to each element in the array
}
}
System.out.print("2D Array elements: ");
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
System.out.print(" " +array[i][j]+ ","); //Output 2D Array
}
}
int[] sumOfRows = new int[array.length];
int[] sumOfColumns = new int[array[0].length];
int sumR = 0;
int sumC = 0;
for(int row = 0; row < array.length; row++){
for(int col = 0; col < array[0].length; col++){ //Sum of rows
sumR += array[row][col];
}
sumOfRows[row] = sumR;
}
System.out.println(" ");
System.out.println("Sum of Rows: " + sumR);
for(int col = 0; col < array.length; col++){
for(int row = 0; row < array[0].length; row++){
sumC += array[row][col];
}
sumOfColumns[col] = sumC;
}
System.out.println("Sum of Columns:" + sumC);
}