为什么最后一个输入是存储?

时间:2016-11-27 18:24:55

标签: java printing openjdk

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

1 个答案:

答案 0 :(得分:1)

您在正在创建的所有inicio个实例中使用相同的lados实例:

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

如果您希望在每次迭代时不要覆盖信息,则应为每个lados创建一个新的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等......