This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
I'm trying to compute the row and column sums of a 2D array but I'm always getting this error java.lang.ArrayIndexOutOfBoundsException: 2
It says there is a error in method computeRowSums but I cannot figure out why it would be array index out of bounds.
// RowColSums.java
// To compute the row and column sums of a 2D array.
import java.util.*;
public class RowColSums {
public static void main(String[] args) {
int row_size, col_size, row, col;
int[][] array2D;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows and columns: ");
row_size = sc.nextInt();
col_size = sc.nextInt();
array2D = new int[row_size][col_size];
System.out.println("Enter values for 2D array: ");
for(row = 0; row < row_size; row++)
for(col = 0; col < col_size; col++)
array2D[row][col] = sc.nextInt();
int[] rowSums = computeRowSums(array2D);
System.out.print("Row sums: ");
System.out.println(Arrays.toString(rowSums));
int[] colSums = computeColSums(array2D);
System.out.print("Column sums: ");
System.out.println(Arrays.toString(colSums));
}
public static int[] computeRowSums(int[][] arr)
{
int i, j;
int[] row_sum = new int[arr[0].length];
for(i = 0; i < arr[0].length; i++)
for(j = 0; j < arr.length; j++)
row_sum[i] += arr[i][j];
return row_sum;
}
public static int[] computeColSums(int[][] arr)
{
int z, r;
int[] col_sum = new int[arr.length];
for(z = 0; z < arr.length; z++)
for(r = 0; r < arr[0].length; r++)
col_sum[z] += arr[z][r];
return col_sum;
}
}
In computeRowSums you got the indices in the wrong order. It should be :
for(i = 0; i < arr[0].length; i++)
for(j = 0; j < arr.length; j++)
row_sum[i] += arr[j][i];
I'm assuming your 2D array has a different number of rows and columns, which explains the exception you got.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I'm new to java program. While executing a program related to threads I got an exception ArrayOutOfBounds. Whats the mistake I made.
Please review my program and reply back soon. I'm stuck with this program.
import java.util.Scanner
public class MatrixMulti implements Runnable {
private int row;
private int col;
private int A[][];
private int B[][];
private int C[][];
public MatrixMulti(int row, int col,int A[][], int B[][], int C[][] ) {
this.row = row;
this.col = col;
this.A = A;
this.B = B;
this.C = C;
}
public void run() {
for(int k = 0; k <=B.length; k++) {
C[row][col] += A[row][k] * B[k][col];
}
}
public static void main(String args[]) {
int row;
int col;
System.out.println("Enter the base of squared matrices");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[][] A=new int[n][n];
int[][] B=new int[n][n];
int[][] C=new int[n][n];
try{
System.out.println("Enter the elements of 1st martix row wise \n");
for(row = 0 ; row < n; row++) {
for (col = 0 ; col < n; col++ ) {
A[row][col] = input.nextInt();
}
}
System.out.println("Enter the elements of 2nd martix row wise \n");
for(row = 0 ; row < n; row++) {
for (col = 0 ; col < n; col++ ) {
B[row][col] = input.nextInt();
}
}
System.out.println(" Matrix A: ");
for(row = 0 ; row < n; row++) {
for (col = 0 ; col < n; col++ ) {
System.out.print(" "+A[row][col]);
}
System.out.println();
}
System.out.println(" Matrix B: ");
for(row = 0 ; row < n; row++) {
for (col = 0 ; col < n; col++ ) {
System.out.print(" "+B[row][col]);
}
System.out.println();
}
int threadcount = 0;
Thread[] thrd = new Thread[n*n];
for(row = 0 ; row < n; row++){
for (col = 0 ; col < n; col++ ) {
thrd[threadcount] = new Thread(new MatrixMulti(row,col,A, B, C));
thrd[threadcount].start();
thrd[threadcount].join();
threadcount++;
}
}
} catch (InterruptedException ie){}
System.out.println(" Product Matrix C: ");
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
System.out.print(" "+C[i][j]);
}
System.out.println();
}
}
}
remove k<= from code
instead write
k< B.length
I am guessing (as you did not post the stacktrace) you need to change
for(int k = 0; k <=B.length; k++)
to
for(int k = 0; k < B.length; k++)
Because by
for (int k=0; k<=B.length; k++)
when k == B.length you still get into the loop, and now you want to get the element at position k. But in an array of a capacity of x, the last element is at position x-1, because the array is 0-based, meaning that the first element is of index 0, and the last, of index array.length - 1. So you by calling B[k] when k == B.length, the index is out of range.
You can change it to
for (int k=0; k<B.length; k++)
Or,
for (int k=0; k<=B.length - 1; k++)
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows/columns in matrix : "); //rows and columns in matrix must be same.
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
System.out.println("Enter the elements in matrix :");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}
Simply add a sum variable which adds up the elements in the two D array like so:
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
sum += matrix[i][j];
}
}
System.out.print("The sum is :");
System.out.println(sum); //Simply for clarity
In Java8
long sum = Arrays.stream(matrix).flatMapToInt(arr -> Arrays.stream(arr)).sum();
I'm a beginner in Java programming. I have created the 2D array that generates random numbers to fill the array.
But now I need to calculate the sum of the rows and columns individually and store the values in a separate table formatted in a 1D array using a method...
This is what I have so far:
import java.util.*;
import java.math.*;
public class Q42 {
public static void main(String[] args) {
//create the grid
final int rowWidth = 4;
final int colHeight = 5;
Random rand = new Random();
int [][] board = new int [rowWidth][colHeight];
//fill the grid
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = rand.nextInt(10);
}
}
//display output
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
//System.out.println();
}
System.out.println();
} //end of main
public static int[] sumTableRows(int[][] table)
{
int rows = table.length;
int cols = table[0].length;
int[] sum = new int[rows];
for(int x=0; x<rows; x++)
for(int y=0; y<cols; y++)
sum[x] += table[x][y];
return sum;
}
} //end of class Main
So if i understand you correctly, this is what you want to do:
You have a 2D array with random values. you want to sum up all the values in every row and put in a variable. Easy. This is how you do it:
public static int[] sumTableRows(int[][] table)
{
int rows = table.length;
int cols = table[0].length;
int[] sum = new int[rows];//make an array for sums
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++){//iterate over all vars in the table array
int temp = table[i][j];//take value in point (i,j)
sum[i] += temp;//sum it in sum[i].
}
}
return sum; //return the 1D array
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The code below will print two square matrices and I need them to perform multiplication between the two matrices but i cant seem to get that part working. I put a comment right before that block of code where the problem is. But for now all it prints is zeros. Iv been looking online at a lot of sites but cant seem to get mine to work.
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
//create the grid
final int rowWidth = 9;
final int colHeight = 9;
Random rand = new Random();
int [][] board = new int [rowWidth][colHeight];
//fill the grid
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = rand.nextInt(10);
}
}
//display output
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
//System.out.println();
}
System.out.println();
}
System.out.println();
int [][] board2 = new int [rowWidth][colHeight];
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board[row2].length; col2++) {
board[row2][col2] = rand.nextInt(10);
}
}
//display output
for(int m = 0; m < board2.length; m++) {
for(int n = 0; n < board[m].length; n++) {
System.out.print(board[m][n] + " ");
}
System.out.println();
}
//error is somewhere here
int[][] calculationMultiplication = new int[rowWidth][colHeight];
for (int l = 0; l < rowWidth; l++) {
for (int t = 0; t < colHeight; t++) {
for (int z = 0; z < rowWidth; z++) {
calculationMultiplication[l][t] = calculationMultiplication[l][t] + board[l][z] * board2[z][t];
}
}
}
//display output
System.out.println("\nProduct of the 2 matrices is ");
for (int i = 0; i < calculationMultiplication.length; i++) {
for (int j = 0; j < calculationMultiplication[0].length; j++) {
System.out.print(calculationMultiplication[i][j] + " ");
}
System.out.println();
}
} //end of main
} //end of class Main
The problem is that you've not filled the board2 array, so all its elements will be 0. In the for loop, you should also assign random values to board2. You are doing it twice for the board array.
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board2[row2].length; col2++) { // notice 'board2[row].length'
board2[row2][col2] = rand.nextInt(10);
}
}
You should do something similar in the for loops where you display the array:
//display output
for (int m = 0; m < board2.length; m++) {
for (int n = 0; n < board2[m].length; n++) { // notice 'board2[row].length'
System.out.print(board2[m][n] + " ");
}
System.out.println();
}
board2 is always zero.
You fill the wrong array here:
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board[row2].length; col2++) {
board[row2][col2] = rand.nextInt(10);
}
}
Basically you just did simple copy paste mistakes that can be avoidable if you used methods. I'll tell you how but first here's how you can discover your mistake:
System.out.println(String.format("%d * %d = %d",board[l][z], board2[z][t], board[l][z] * board2[z][t]));
Add this just before doing the calculation for calculationMultiplication[l][t]. Try if you want...
Anyway getting back to your mistakes, you have populated your first matrix only, the second one contain zeros (verify your code in the for loop for inserting random numbers into the second matrix), therefore any number multiplied by zero is equal to zero.
I haven't looked at all your code, because it contain a lot of copy paste which confused you and could confuse any one as well, so here's a better way to avoid mistakes in printing the matrix and inserting random numbers:
Printing:
void printMatrix(int[][] matrix){
for(int row =0; row < numOfRows; row++){
for(int col =0; col < numOfCols; col++){
System.out.print(matrix[row][col]+" ");
}
System.out.println(); // new line
}
}
Inserting:
void insertMatrix(int[][] matrix){
for(int row =0; row < numOfRows; row++){
for(int col =0; col < numOfCols; col++){
matrix[row][col] = rand.nextInt(10); // rand must be declared outside any method
}
}
}
Putting all together:
import java.util.*;
public class Main {
// create the grid
final static int rowWidth = 9;
final static int colHeight = 9;
static Random rand;
public static void main(String[] args) {
rand = new Random();
int[][] board = new int[rowWidth][colHeight];
int[][] board2 = new int[rowWidth][colHeight];
int[][] calculationMultiplication = new int[rowWidth][colHeight];
// fill
insertMatrxi(board);
// display output
printMatrix(board);
System.out.println();
// fill
insertMatrxi(board2);
// display output
printMatrix(board2);
for (int l = 0; l < rowWidth; l++) {
for (int t = 0; t < colHeight; t++) {
for (int z = 0; z < rowWidth; z++) {
calculationMultiplication[l][t] += board[l][z] * board2[z][t];
}
}
}
// display output
System.out.println("\nProduct of the 2 matrices is ");
printMatrix(calculationMultiplication);
} // end of main
public static void printMatrix(int[][] matrix) {
for (int row = 0; row < rowWidth; row++) {
for (int col = 0; col < colHeight; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println(); // new line
}
}
public static void insertMatrxi(int[][] matrix) {
for (int row = 0; row < rowWidth; row++) {
for (int col = 0; col < colHeight; col++) {
matrix[row][col] = rand.nextInt(10);
}
}
}
} // end of class Main
This question already has answers here:
Converting 1-D String array to 2-D char array
(4 answers)
Closed 9 years ago.
Good day everyone, for the past couple of days I have been working on converting a 1D string array to a 2D char array. My 1D array works fine(zero issues) but when I convert to the 2D char array it only prints out the first row. Below is my code. Any feedback is appreciated. Thanks!
for(int i = 0; i < array1.length; i++) //prints out array
{
System.out.println("1d " + number[i]); //prints the line from the file
}
final int ROWS = 7;
final int COLS = 5;
char[][] 2darray = new char [ROWS][COLS];
for (int i = 0; i < array.length; i++)
{
2darray[i]= array1[i].toCharArray();
}
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
System.out.print(2darray[row][col]);
}
System.out.println();
}
You cannot have variables start with a number in Java. I suggest changing your variables accordingly and trying it out.
char[][] array2 = new char [ROWS][COLS];
for (int i = 0; i < array.length(); i++)
{
array2[i]= array1[i].toCharArray();
}
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
System.out.print(array2[row][col]);
}
System.out.println();
}
See Comments
for(int i = 0; i < array1.length; i++) //prints out array
{
// Why did you use number ?
System.out.println("1d " + array1[i]); //prints the line from the file
}
// You don't need these now.
// final int ROWS = 7;
// final int COLS = 5;
// This will initialize 2darray of size as required according to length of array1
char[][] 2darray = new char [array1.length][];
for (int i = 0; i < array1.length; i++) // What is `array`?
{
2darray[i]= array1[i].toCharArray();
}
for (int row = 0; row < 2darray.length; row++) // Use actual size of 2darray row
{
for (int col = 0; col < 2darray[i].length; col++) // use actual size of 2darray column
{
System.out.print(2darray[row][col]);
}
System.out.println();
}