Java: Storing values in 2D Array -
i have problem storing values in multidimensional array. main concept of thought have arraylist called user_decide , transform in array. so, decide array looks [1, 45, 656, 8, 97, 897], rows don't have same number of elements. then, split replace [,] , spaces , store each value individually in 2d array. so, split "," , seek store each value in different position. seems printed great, cut[j] want store, java.lang.nullpointerexception, don't get. count variable count = user_decide.size()
string [] decide = user_decide.toarray(new string[user_decide.size()]); (int = 0; < count; ++){ decide[i] = decide[i].replaceall("\\s", "").replaceall("\\[","").replaceall("\\]", ""); } string [][] data1 = new string[count][]; (int = 0; < count; i++){ string [] cutting = decide[i].split("\\,"); (int j = 0; j < cut.length; j++){ system.out.println(cut[j]); data1[i][j] = cut[j]; } } another question why cannot store in int [][] array? there way that?
thank lot.
** edit **
i made edit reply after accepted question. trying store in 2d int array.
string [][] data1 = new string[user_decide.size()][]; int [][] info = new int [user_decide.size()][]; (int = 0; < user_decide.size(); i++){ data1[i] = decide[i].split("\\,"); (int j = 0; j < data1[i].length; j++) { data[i] = new int [data1[i].length]; data[i][j] = integer.parseint(data1[i][j]); system.out.println(data1[i][j]); } }
ivaylo strandjev's reply shows reason problem. there's much simpler solution:
string [][] data1 = new string[count][]; (int = 0; < count; i++){ data1[i] = decide[i].split("\\,"); system.out.println(arrays.tostring(data1[i])); } also, don't need escape comma.
edit
saw edit. there big mistake, see comment in code:
string [][] data1 = new string[user_decide.size()][]; int [][] info = new int [user_decide.size()][]; (int = 0; < user_decide.size(); i++){ data1[i] = decide[i].split("\\,"); (int j = 0; j < data1[i].length; j++) { data[i] = new int [data1[i].length]; // line has prior // inner loop, or else you'll overwrite lastly number. data[i][j] = integer.parseint(data1[i][j]); system.out.println(data1[i][j]); } } if want int[], do:
int [][] info = new int [user_decide.size()][]; (int = 0; < user_decide.size(); i++){ string[] temp = decide[i].split(","); data[i] = new int [temp.length]; (int j = 0; j < temp.length; j++){ data[i][j] = integer.parseint(temp[j]); system.out.println(data1[i][j]); } } there nicer ways, don't know why using user_decide.size() ( collection) status , decide[i] (an array) within loop. there's no reason can think of mixing this, lead errors.
java arrays multidimensional-array
No comments:
Post a Comment