Search code examples
javaarraysindexoutofboundsexception

How do I swap columns with a specific indexes in java 2d arrays?


So I've been trying to solve following problem:

Given a two-dimensional array (matrix) and the two numbers: i and j. Swap the columns with indexes i and j within the matrix.

Input contains matrix dimensions n and m, not exceeding 100, then the elements of the matrix, then the indexes i and j.

Sample Input 1:

  • 3 4
  • 11 12 13 14
  • 21 22 23 24
  • 31 32 33 34
  • 0 1

Sample Output 1:

  • 12 11 13 14
  • 22 21 23 24
  • 32 31 33 34

In order to solve it, I wrote following code:

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int rows = scanner.nextInt();
        int tables = scanner.nextInt();
        int[][] matrix = new int[rows][tables];

        int i = scanner.nextInt();
        int j = scanner.nextInt();

        for (int w = 0; w < rows; w++){
            int temp = matrix[w][i];
            matrix[w][i] = matrix[w][j];
            matrix[w][j] = temp;
        }

        System.out.print(matrix);
    }
}

And the error is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 11 out of bounds for length 4 at Main.main(Main.java:15).

What might be the problem and solution to it?


Solution

  • Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 11 out of bounds for length 4 at Main.main(Main.java:15).

    Above error is because you are directly reading values into i and j but you forgot setting the values inside the matrix[][] as said by vince and jim in the comments.

    Use loop to set the values

      for(int k=0;k<rows;k++){
          for(int l=0;l<cols;l++){
                 matrix[k][l]=scanner.nextInt();
          }   
       }
    

    and then loop through rows to swap values

    Here goes the code

    Live: https://onlinegdb.com/rJJ-kMTUL

    import java.util.*;
    
    class Main {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int rows = scanner.nextInt();
            int cols = scanner.nextInt();
            int[][] matrix = new int[rows][cols];
            for(int k=0;k<rows;k++){
             for(int l=0;l<cols;l++){
                 matrix[k][l]=scanner.nextInt();
             }   
            }
            int i = scanner.nextInt();
            int j = scanner.nextInt();
            for(int k=0;k<rows;k++){
            int temp =  matrix[k][i];
            matrix[k][i] = matrix[k][j];
            matrix[k][j]=temp;      
            }
             for(int k=0;k<rows;k++){
             for(int l=0;l<cols;l++){
                 System.out.print( matrix[k][l]+" ");
             }
             System.out.println();
            }
        }
    }