I was wondering if someone could respond by fixing my code so I don\'t get this
ID: 3528049 • Letter: I
Question
I was wondering if someone could respond by fixing my code so I don't get this output:
Elements in 2D Array:
9
2
5
4
7
4
4
5
10
2
7
4
5
9
0
3
0
1
6
10
Sum of rows: 97
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at number3.sumCols(number3.java:48)
at number3.main(number3.java:21)
The code is:
import java.util.*;
import java.io.*;
import java.util.Random;
public class number3
{
private static int i = 0;
private static int j = 0;
public static void main(String[]args)
{
int[][] randArray = new int[5][4];
Random randomizer = new Random();
for (i = 0; i < randArray.length; i++){
for (j = 0; j < randArray[i].length; j++){
randArray[i][j] = randomizer.nextInt(11);
}
}
print(randArray);
sumRows(randArray);
sumCols(randArray);
}
public static void print(int[][] randArray)
{
System.out.println("Elements in 2D Array:");
for (i = 0; i < randArray.length; i++){
for (j = 0; j < randArray[i].length; j++){
System.out.println(randArray[i][j]);
}
}
}
public static void sumRows(int[][] randArray)
{
int[] sumOfRows = new int[randArray.length];
int sumOfR = 0;
for (int row = 0; row < randArray.length; row++){
for (int col = 0; col < randArray[row].length; col++){
sumOfR += randArray[row][col];
}
sumOfRows[row] = sumOfR;
}
System.out.println("Sum of rows: " + sumOfR);
}
public static void sumCols(int[][] randArray)
{
int[] sumOfCols = new int[randArray[i].length];
int sumOfC = 0;
for (int col = 0; col < randArray.length; col++){
for (int row = 0; row < randArray[col].length; row++){
sumOfC += randArray[col][row];
}
sumOfCols[col] = sumOfC;
}
System.out.println("Sum of columns: " + sumOfC);
}
}
Explanation / Answer
public static void sumRows(int[][] randArray)
{
int[] sumOfRows = new int[randArray.length];
for (int row = 0; row < randArray.length; row++)
{
int sumOfR = 0;
for (int col = 0; col < randArray[row].length; col++)
{
sumOfR += randArray[row][col];
}
sumOfRows[row] = sumOfR;
}
System.out.println("Sum of rows: " + sumOfR);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.