user1110191
user1110191

Reputation: 67

Convert 1d array to multidimensional array in java

Lets say I have 1d array

String teams[]={"Michael-Alex-Jessie","Shane-Bryan"}; 

and I want to convert it to multidimensional array which will be like this

String group[][]={{Michael,Alex,Jessie},{Shane,Bryan}}. 

I try to use delimeter but for unknown reason I cannot assign the value of 1d to 2d array. It said incompatible types. Please any help will be much appreciated. Here is my code.

String [][]groups ; 
String teams[]={"Michael-Alex-Jessie","Shane-Bryan"};
int a=0,b=0;
String del ="-/"; 

    for (int count = 0; count < teams.length; count++)
    {
       groups[a][b] = teams[count].split(del);
       a++;
    }

Upvotes: 0

Views: 1198

Answers (4)

kbdjockey
kbdjockey

Reputation: 897

String.split() return an Array of String, not a String

Upvotes: 0

rsp
rsp

Reputation: 23373

You need to assign an array value, not a cell value:

   groups[count] = teams[count].split(del);

Upvotes: 0

AlexR
AlexR

Reputation: 115398

Type of group[a][b] is String but you are attempting to assign string array (i.e. String[]) there.

This is what you really want to do:

for (int count = 0; count < teams.length; count++) {
   groups[count] = teams[count].split(del);
}

Upvotes: 3

andrey
andrey

Reputation: 842

Yoy can't assign array of Strings returned by "teams[count].split(del)" to String

public class qq {
String[][] groups;
String teams[] = { "Michael-Alex-Jessie", "Shane-Bryan" };
int a = 0, b = 0;

public void foo() {
    String del = "-/";
    groups = new String[teams.length][];
    for (int count = 0; count < teams.length; count++) {
        groups[count] = teams[count].split(del);
        a++;
    }
}
}

Upvotes: 0

Related Questions