tags:

views:

82

answers:

3

I am trying to copy certain elements of an array into another. For example, I want to copy index 0 of lines into index 0 of links, index 3 of lines into index 1 of links, and so on (every 3 element of lines basically basically).

What I have so far keeps getting me an ArrayIndexOutOfBound error. Thank you for your help!

String[] lines = inputString.split(System.getProperty("line.separator"));
String[] links = new String[lines.length]; 
int j = 0;

for (int i = 0; i < lines.length; i++) {
   links[i] = lines[j+3];
   j++;
   System.out.println(links[i]);
}
+4  A: 

It sounds like you need to be incrementing i by 3, rather than adding 3 to j (but then incrementing j by just 1). In fact, you don't need two variables at all:

for (int i = 0; i < lines.length; i += 3) {
    links[i / 3] = lines[i];
}

You should also change your code to only create the array to be as large as you need:

String[] links = new String[lines.length / 3];

Just for the sake of interest, let's have a look at what your code was actually trying to do, in terms of assignments:

links[0] = lines[3];
links[1] = lines[4];
links[2] = lines[5];
// etc

As you can see, this is just offsetting the index, rather than multiplying it... and as soon as i was lines.length-3, you'd end up with

links[lines.length - 3] = lines[lines.length]; // Bang!
Jon Skeet
A: 

A few problems:

1. You probably want this:

for (int i = 0; i < lines.length; i++) {
    links[i] = lines[j+3];

To look like this:

for (int i = 0; i < links.length; i++) {
    links[i] = lines[j * 3];

2. Well, yes. You are going out of bounds. Let's say lines is 12 elements. links is the same size, so you're trying to read from element 15 / 36 (depending on my correction in #1)

The solution is to make links smaller:

String[] links = new String[(int)(lines.length / 3)];

Along with the correction in #1.

Mike Caron
A: 

Jon Skeet has the right idea. What might be useful is to learn how to debug these things yourself. Say that lines.length is 5, meaning also that links.length is 5. What happens if you trace every iteration of the for loop?

i        |      j       |     j + 3       
-----------------------------------------
0               0               3       
1               1               4
2               2               5

It'll break on this 3rd iteration. You can see that you're not accessing every three elements at all, but every element, and you're storing it in an offset position, which causes your index out of bounds exception.

Claudiu