0

I have an String array called data which contains :

data: [Solaergy, 3255, Solagy, 3635, Soly, 36235, Solar energy, 54128, Solar energy, 54665, Solar energy, 563265]

Now i want to split data into two arrays title and isbn (of books):

String[] titles = new String[data.length];
String[] isbnS = new String[data.length];
for (int i = 0; i < data.length; i += 2) {
    titles[i] = data[i];
    isbnS[i] = data[i + 1];
}
    System.out.println("titles: " + Arrays.toString(titles));
    System.out.println("isbnS: " + Arrays.toString(isbnS));

My problem is that there is a null value after each value in each two arrays:

titles: [Solaergy, null, Solagy, null, Soly, null, Solar energy, null, Solar energy, null, Solar energy, null]
isbnS: [3255, null, 3635, null, 36235, null, 54128, null, 54665, null, 563265, null]

I want to be like this:

titles: [Solaergy, Solagy, Soly, Solar energy, Solar energy, Solar energy]
isbnS: [3255, 3635, 36235, 54128, 54665, 563265]

3 Answers 3

5

You got the indices wrong :

String[] titles = new String[data.length/2];
String[] isbnS = new String[data.length/2];
int count = 0;
for (int i = 0; i < data.length; i += 2) {
    titles[count] = data[i];
    isbnS[count] = data[i + 1];
    count++;
}
Sign up to request clarification or add additional context in comments.

Comments

3
for (int i = 0, j=0; i < data.length; i += 2, j++) {
    titles[j] = data[i];
    isbnS[j] = data[i + 1];
}

Comments

0

I think what you're trying to do is put one element n one array and the next one in the other.

However, you're trying to store integers in a string array.

This is what I would do:

String[] titles = new String[data.length/2];
int[] isbnS = new int[data.length/2];
int j=0;
for(int i=0; i<data.length; i+=2)
{
    titles[j] = data[i];
    isbnS[j++] = data[i+1];
}

1 Comment

Interesting that you can write the content of the data array into two different array types without handling/casting them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.