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]
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++;
}
for (int i = 0, j=0; i < data.length; i += 2, j++) {
titles[j] = data[i];
isbnS[j] = data[i + 1];
}
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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.