Created
November 19, 2015 13:12
-
-
Save eMahtab/297419cb805fe93346c0 to your computer and use it in GitHub Desktop.
Java program to take 2D array as input from user.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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