随即函数求距离的疑惑,有很多不懂的,求解释
public class Point {int x,y;
public Point(int x,int y){
this.x=x;
this.y=y;
}
public int distance(){
return (int)Math.sqrt(x*x+y*y);
}
public static void main(String args[])
{
Point p[]=new Point[9];
for(int i=0;i<p.length;i++)
{
p[i]=new Point((int)(Math.random()*10+1),(int)(Math.random()*10+1));//产生随机的点
}
Point temp = null;//排序
for (int i = 0; i < 8; i++)
{
for (int j = i + 1; j < 9; j++)
{
if (p[i].distance() > p[j].distance())
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
for (int i =0; i <9; i++)
{
System.out.print(i+1+".产生的点("+p[i].x+","+p[i].y+") 到原点的距离是:");
System.out.println(p[i].distance());
}
}
}
老师处了个作业,在网上找到这个代码,但是有很多看不懂的,比如说this,还有p[i].distance() > p[j].distance()这一个是怎么调用前面的distance()方法的,distance()里面的x和y的值又是怎么和数组联系起来运算的。真心不懂了,大侠给点指示
----------------解决方案--------------------------------------------------------
public class Point {
int x,y;
public Point(int x,int y){//这是构造方法
this.x=x;
this.y=y;
}
public int distance(){//这是求解随即生成的点到原点的距离
return (int)Math.sqrt(x*x+y*y);
}
public static void main(String args[])
{
Point p[]=new Point[9];
for(int i=0;i<p.length;i++)
{
p[i]=new Point((int)(Math.random()*10+1),(int)(Math.random()*10+1));//产生随机的点
}
Point temp = null;//排序
for (int i = 0; i < 8; i++)
{
for (int j = i + 1; j < 9; j++)
{
if (p[i].distance() > p[j].distance())
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
for (int i =0; i <9; i++)
{
System.out.print(i+1+".产生的点("+p[i].x+","+p[i].y+") 到原点的距离是:");//循环输出
System.out.println(p[i].distance()); // 此处循环一次,
//那么p[i]就实例化了就是一个Point类的一个对象,那么就可以调用此类里的distance方法
}
}
}
不懂,再问 qq 1258601435
----------------解决方案--------------------------------------------------------