简体   繁体   中英

Java Integer.ParseInt bug

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?

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]);

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM