package my;
public class Point
{
public int x; // 横坐标
public int y; // 纵坐标
// 到另一个点的距离
public int manhattan ( Point o ) // 参数为另一个Point对象,这个语法参考:网盘里第8章下面的补充教程
{
int dx = o.x - this.x;
int dy = o.y - this.y;
if(dx < 0)
{
dx = 0 -dx;
}
if(dy < 0)
{
dy = 0 -dy;
}
return dx + dy;
}
}
2 调用
package my;
public class HelloWorld
{
public static void main(String[] args)
{
Point p1 = new Point();
p1.x = 0;
p1.y = 0;
Point p2 = new Point();
p2.x = 1;
p2.y = 1;
int d = p1.manhattan( p2 );
System.out.println("曼哈顿距离: " + d);
}
}