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

标签 printing java

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

最佳答案

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

 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 等...

关于printing - 为什么最后一个输入是存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40832338/

相关文章:

java - 从 shp 文件读取坐标并计算距离

java - 为什么 Toast.makeText(...) 和 toastObj.makeText(...) 运行方式不同?

java - 旋转已转换为像素的纬度、经度坐标

java - 算法的性能突然提高了约 10 倍

php - 从 HTML 屏幕打印动态页眉或页脚

css - 为什么 Chrome 打印 CSS 仿真和打印预览之间存在如此大的差异?

java - 我将如何从 java 程序打印文本? ( java )

ruby - 如何打印方法的参数名称

javascript - PHP/HTML 将表格导出为 pdf?

java - 如何将反斜杠后跟 't' 或文件路径中转义字符中的任何其他字母或字符替换为 java 中的正斜杠?