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);
}
}
}
我究竟做错了什么?我想将ponits(x,y)存储在数组的索引中,但最后一个输入存储在所有索引中……如果有人共享我想要的,也许还有其他方法可以做我想做的事情它。
输入:
1
2
3
4
5
6
输出:
5
6
5
6
5
6
预期输出:
1
2
3
4
5
6
您inicio
在lados
创建的所有实例中使用相同的实例:
for(int i=0; i<3; i++){
inicio.x = leer.nextInt();
inicio.y = leer.nextInt();
arreglo[i] = new lados(inicio);
}
如果希望该信息在每次迭代时都不会被覆盖,则应该为每个拉多创建一个新的punto实例。尝试:
for(int i=0; i<3; i++){
inicio = new punto()
inicio.x = leer.nextInt();
inicio.y = leer.nextInt();
arreglo[i] = new lados(inicio);
}
按照惯例,课程应以大写字母开头:Punto,Lados等。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句