Skip to content

Instantly share code, notes, and snippets.

@eMahtab
Created November 19, 2015 13:12
Show Gist options
  • Save eMahtab/297419cb805fe93346c0 to your computer and use it in GitHub Desktop.
Save eMahtab/297419cb805fe93346c0 to your computer and use it in GitHub Desktop.
Java program to take 2D array as input from user.
import java.util.Scanner;
public class TwoDArrayInput{
public static void main(String args[]){
System.out.print("Enter 2D array size : ");
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
int columns=sc.nextInt();
System.out.println("Enter array elements : ");
int twoD[][]=new int[rows][columns];
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=sc.nextInt();
}
}
System.out.print("\nData you entered : \n");
for(int []x:twoD){
for(int y:x){
System.out.print(y+" ");
}
System.out.println();
}
}
}
@Manmeet121999
Copy link

import java.util.Scanner;
public class Multidimensional_Arrays {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int flates[][] = new int[2][3];
System.out.println("Enter array elements = ");
for (int i = 0; i < flates.length; i++) {
for (int j = 0; j <= flates.length; j++) {
flates[i][j] = sc.nextInt();
System.out.print(flates[i][j] + " ");
}
}
System.out.println();
//reverse
System.out.println("Reverse of Multi-dimensional Array");
for (int i = flates.length - 1; i >= 0; i--) {
for (int j = flates.length; j >= 0; j--) {
System.out.print(flates[i][j] + " ");
}
}
}
}

@Anand4510
Copy link

Bro your "x" and "y" are the size of row and column, so in the line
// Let's consider your row =2, and column=2
array[x][y] = input.nextInt();
array[2][2] = 20 // let's consider ur 1st input is 20.
You are directly giving input to, the 2nd row 2nd column element.
So for the first input i.e., array[2][2] will take input as 20. In the next iteration, again you are giving the input for the same array[2][2]th element.
There you will get the ArrayIndexOutOfRange
After

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment