I am writing a code where inputs will be taken from the user and stored in a 2-Dimensional dynamic array. We know the no. of rows of the array. But the number of columns of the array is dynamic.
The input will be in the form as shown below:
3
sghjhlklj
ghgh
ytyhuj
Since 3 is entered first, there would be three subsequent strings which have to be stored in an array.
Following is the code snippet that I have written. But it shows array index out of bounds exception.
import java.util.Arrays;
import java.util.Scanner;
class Main
{
// Read a String from the standard input using Scanner
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Integer no = in.nextInt();
System.out.println("You entered string "+no);
int z = 0,y=0 ;
char[][] arr = new char[no][];
for(z=0 ; z<no ; z++)
{
String s = in.nextLine();
String[] arrOfStr = s.split("");
for( y =0 ; y<arrOfStr.length ; y++)
{
arr[z][y]=arrOfStr[y].charAt(0);
}
}
in.close();
}
}