0

I have something like the below:

char[] array = new char[5];
String a = "HELLO";
String b = "WORLD";
array[0] = a.toCharArray();
array[1] = b.toCharArray();

I get error "incompatible types, char[] cannot be converted to char". My final product I'd like something like the below:

array = {{H},{E},{L},{L},{O}},{{W},{O},{R},{L},{D}};

array becomes a [2][5] array in the end result. Is toCharArray() the incorrect method to use?

5 Answers 5

2

You need to have a double array. Something like

char[][] arr = new char[2][];
arr[0] = a.toCharArray();
Sign up to request clarification or add additional context in comments.

4 Comments

Well...you can't have a jagged array without a defined row size.
@makoto36 yeah, mental slip up there!
I feel so silly for overlooking something so simple. All the best, this worked. Just curious, and while this is only somewhat related, how do I check the length of a ragged array? Something like a two-dimensional array with undefined lengths, how do I check the length of individual sub-arrays? array.length will give the number of elements in main arrays, will array[].length give the lengths of inner arrays?
@riista No, however you could you use arr[0].length to get the length of the first element, but you need to do that one by one.
1

You need an array of arrays. Something like this:

char[][] array = new char[5][];

Comments

1

You have to use toCharArray to get a char[] back; the problem is where you put it after you extract it.

Change your array variable to be a char[][], and define it as such:

char[][] array = new char[2][5];

Note that the result won't exactly be {{H},{E},{L},{L},{O}},{{W},{O},{R},{L},{D}}; it'd be more like {{H, E, L, L, O}},{{W, O, R, L ,D}}.

Comments

1

You need an array of arrays

char[][] arr = new char[5][];
arr[0] = a.toCharArray();

Comments

1
char[] array = new char[5];
String a = "HELLO";
String b = "WORLD";
array[0] = a.toCharArray();
array[1] = b.toCharArray();

What if a and b are not of the same length ? Your method and the ones proposed by others are very limited/specific and not flexible. Try this instead to make abstraction of the length of the String.

 ArrayList<char[]> array = new ArrayList();
 String a = "HELLO";
 String b = "WORLD";
 array.add(a.toCharArray());
 array.add(b.toCharArray());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.