This code shows error in eclipse: array index out of bound

package Array;

import java.util.Scanner;

public class TwoDArray {
public static void main(String[] args) {

	int[][] arr = takeinput();
	display(arr);

}

public static int[][] takeinput() {
	Scanner s = new Scanner(System.in);
	System.out.println("Enter the number of rows");
	int rows = s.nextInt();
	int[][] arr = new int[rows][];
	for (int row = 0; row < rows; row++) {
		System.out.println("Enter the number of cols for row " + row);
		int cols = s.nextInt();
		arr[row] = new int[cols];
		for (int col = 0; col < cols; col++) {
			System.out.println("Enter the value for row " + row + "and col" + col);
			arr[rows][col] = s.nextInt();
		}
	}
	return arr;
}

public static void display(int[][] arr) {
	for (int row = 0; row < arr.length; row++) {
		for (int col = 0; col < arr[row].length; col++) {
			System.out.print(arr[row][col] + " ");
		}
		System.out.println();
	}
}

}

Hey @kalindiyadav5
Actually you are confused between row and rows
Correct code :
import java.util.Scanner;

public class TwoDArray {
public static void main(String[] args) {
int[][] arr = takeinput();
display(arr);
}

public static int[][] takeinput() {
	Scanner s = new Scanner(System.in);
	System.out.println("Enter the number of rows");
	int rows = s.nextInt();
	int[][] arr = new int[rows][];
	for (int row = 0; row < rows; row++) {
		System.out.println("Enter the number of cols for row " + row);
		int cols = s.nextInt();
		arr[row] = new int[cols];
		for (int col = 0; col < cols; col++) {
			System.out.println("Enter the value for row " + row + "and col" + col);
			arr[row][col] = s.nextInt();
		}
	}
	return arr;
}

public static void display(int[][] arr) {
	for (int row = 0; row < arr.length; row++) {
		for (int col = 0; col < arr[row].length; col++) {
			System.out.print(arr[row][col] + " ");
		}
		System.out.println();
	}
}

}

1 Like

Thank you . I got it.