有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中寻找在每次迭代时向数组输入(x,y)的方法

我正在寻找在java中数组调用的每个实例上添加一个点(x,y) 这就是我想做的 声明一个数组,如

int [] weight = new int[100];

我希望在下一步中增加价值

 weight.add(3,4);
 weight.add(5,6);

我想要的想法是,当我进行这样的迭代时

for(int i =0;i< weight.length;i++)
     print "Weight"+i+ "has"+ weight[i] 

应该打印出来

       Weight 0 has (3,4);

共 (2) 个答案

  1. # 1 楼答案

    创建一个私有内部类Point,如下所示:

    private static class Point {
        int x;
        int y;
        //...........
    }
    

    然后,为每个x, y对创建一个点对象,并将其放入weight

  2. # 2 楼答案

    我会为每个点创建一个类,其中包含x和y坐标。。。使用类似于

    class Point{
        public Point(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
    

    然后,不制作整数数组,而是制作点数组。。。 比如

    //create array of points size 100
    Point [] weight = new Point[100];
    
    //add point to array
    int i = 0; //set this to the index you want the point at
    weight[i] = new Point(0, 0); //add whatever point you want to index i
    
    //then you can loop through your array of points and print them out
    for (int i = 0; i < weight.length; i++){
    
        System.out.println("Weight " + i + " has (" + weight[i].x + "," + weight[i].y + ");\n"
    }
    

    在我看来,将x和y坐标抽象为点类是一个更好的设计。它将帮助你在编程时更好地在脑海中记录数据。此外,您可以向point类添加方法,例如double distance(Point other),以返回两点之间的距离