Uriel Castro Uriel Castro - 7 days ago 5
Java Question

why just the last input is storage?

import java.util.Scanner;
public class error{

private static class punto{
int x, y;
}
private static class lados{
punto inicio = new punto();

public lados(punto inicio1){
inicio=inicio1;

}
public punto getInicio(){
return inicio;
}
public void setInicio(punto inicio){
this.inicio = inicio;
}

}

public static void main(String[]args){
Scanner leer = new Scanner(System.in);
punto inicio = new punto();
lados arreglo[] = new lados[100];

for(int i=0; i<3; i++){
inicio.x = leer.nextInt();
inicio.y = leer.nextInt();
arreglo[i] = new lados(inicio);
}

for(int i=0; i<3; i++){
System.out.println(arreglo[i].getInicio().x);
System.out.println(arreglo[i].getInicio().y);
}
}
}


what am I doing wrong?
I want to storage ponits(x,y) in an index on an array
but just the last input is storaged in all index...
maybe there is other way to do what I want to do, if someone share it I'd love it.

input:

1
2
3
4
5
6


output:

5
6
5
6
5
6


expected output:

1
2
3
4
5
6

Answer

You use the same inicio instance in all lados instances you are creating :

 for(int i=0; i<3; i++){
            inicio.x = leer.nextInt();
            inicio.y = leer.nextInt();
            arreglo[i] = new lados(inicio);
  }

You should create a new instance of punto for each lados if you want that the information to not be overwritten at each iteration. Try that :

 for(int i=0; i<3; i++){
            inicio = new punto()
            inicio.x = leer.nextInt();
            inicio.y = leer.nextInt();
            arreglo[i] = new lados(inicio);
  }

By convention, classes should be written with uppercase : Punto, Lados, etc...

Comments