0

Initial string = 61440 <CARRE> 150 381 188 419 </CARRE>

I've split this string into an array, which now contains the coordinates

String[] coord = t.group(2).split(" ");

The resulting output was :

les coord est :150 381 188 419
i = 0 et sa valeur est :150
i = 1 et sa valeur est :381
i = 2 et sa valeur est :188
i = 3 et sa valeur est :419

for which I did a for loop:

formeCoord = new int[coord.length];
formeCoord[i] = Integer.parseInt(coord[i]);

Now I'd expect an output with an int array with all the coordinates. But instead the output is :

Voici la valeur de i =0 et sa valeur int: 0
Voici la valeur de i =1 et sa valeur int: 0
Voici la valeur de i =2 et sa valeur int: 0
Voici la valeur de i =3 et sa valeur int: 419

Here is the for loop :

for (int i = 0; i<formeCoord.length; i++){
    System.out.println("Voici la valeur de i ="
        + i
        + "et sa valeur int: "
        + formeCoord[i]);
}

Does anyone know what I'm doing wrong?

5
  • 2
    Are you sure you populated your array (i.e. formeCoord) correctly? Commented Feb 26, 2013 at 15:51
  • 6
    Post the for loop.. Commented Feb 26, 2013 at 15:51
  • Well when i system.printout the array "coord" it show's up correctly. Commented Feb 26, 2013 at 15:52
  • I mean the loop where you set up formecoord. Most likely dukeling's answer is correct but you havent posted the relevant bit of code. Commented Feb 26, 2013 at 15:53
  • 2
    Not that for loop, the other one. The one containing these lines: formeCoord = new int[coord.length]; formeCoord[i] = Integer.parseInt(coord[i]); Commented Feb 26, 2013 at 15:55

2 Answers 2

6

It seems you're creating a new array every iteration, instead of adding to it.

Presumably your code looks like this:

for (int i = 0; i < coord.length; i++)
{
  formeCoord = new int[coord.length];
  formeCoord[i] = Integer.parseInt(coord[i]);
}

You need to change it to:

formeCoord = new int[coord.length];
for (int i = 0; i < coord.length; i++)
  formeCoord[i] = Integer.parseInt(coord[i]);
Sign up to request clarification or add additional context in comments.

1 Comment

You could set up your IDE to put every variable/Object that can be final to final. It would have helped to find this bug
2

If you are looping over the following code...

formeCoord = new int[coord.length];
formeCoord[i] = Integer.parseInt(coord[i]);

you are resetting formeCoord every time apart from the last time it gets run

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.