java - Convert String into a two dimensional array -


i try convert string

s=[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]
2 dimensional array this
{4, 2, 2, 4},
{3, 4, 5, 6},
{6, 7, 8,9},
{3, 2, 1, 4}

by use code

 int e=s.replaceall("\\[", "").replaceall(" ","").replaceall("],","]").length();         string[] rows1 = s.replaceall("\\[", "").replaceall(" ","").replaceall("],","]").substring(0, e-2).split("]");          string[][] matrix1 = new string[4][4];          int r1 = 0;         (string row1 : rows1) {             matrix[r1++] = row1.split(",");         }          system.out.println(arrays.deeptostring(matrix1)); 

but have problem

exception in thread "main" java.lang.arrayindexoutofboundsexception: 3 @ test.main(test.java:94)

can me find solution?

i think code you. read comments carefully.

     string s="[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";      s=s.replace("[","");//replacing [ ""      s=s.substring(0,s.length()-2);//ignoring last 2 ]]      string s1[]=s.split("],");//separating "],"       string my_matrics[][] = new string[s1.length][s1.length];//declaring 2 dimensional matrix input       for(int i=0;i<s1.length;i++){          s1[i]=s1[i].trim();//ignoring space if string s1[i] has          string single_int[]=s1[i].split(", ");//separating integers ", "           for(int j=0;j<single_int.length;j++){              my_matrics[i][j]=single_int[j];//adding single values          }      }       //printing result      for(int i=0;i<4;i++){          for(int j=0;j<4;j++){              system.out.print(my_matrics[i][j]+" ");          }          system.out.println("");      } 

[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]

logic: 1) replacing [ "" have-> 4, 2, 2, 4], 3, 4, 5, 6], 6, 7, 8, 9], 3, 2, 1, 4]]

2) separating "]," have->

a) 4, 2, 2, 4

b) 3, 4, 5, 6

c) 6, 7, 8, 9

d) 3, 2, 1, 4

3) separating b c d ", " have->

a) a) 4 b) 2 c) 2 d) 4

b) a) 3 b) 4 c) 5 d) 6

c) a) 6 b) 7 c) 8 d) 9

d) a) 3 b) 2 c) 1 d) 4


Popular posts from this blog