在java中寻找在每次迭代时向数组输入(x,y)的方法
我正在寻找在java中数组调用的每个实例上添加一个点(x,y) 这就是我想做的 声明一个数组,如在java中寻找在每次迭代时向数组输入(x,y)的方法,java,Java,我正在寻找在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] 我会为每个点创建一个类,其中包含一个x
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]
我会为每个点创建一个类,其中包含一个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"
}
然后,不制作整数数组,而是制作点数组。。。
类似于
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"
}
//创建大小为100的点数组
点[]权重=新点[100];
//将点添加到阵列
int i=0//将该值设置为点所在的索引
权重[i]=新点(0,0)//添加任何要索引i的点
//然后,您可以在点数组中循环并打印出来
对于(int i=0;i
在我看来,将x和y坐标抽象为点类是一个更好的设计。它将帮助您在编程时更好地在头脑中跟踪数据。此外,您可以向点类添加方法,例如
双距离(点其他)
若要返回两点之间的距离…请创建一个私有的内部类点
,如下所示:
private static class Point {
int x;
int y;
//...........
}
然后,对于每个
x,y
对,创建一个点对象,并将其放入weight
从技术上讲,distance
应该是一种只需要一个点的方法。…@SanjayT.Sharma你说得对……我很忙……谢谢你指出这一点