编写一个Point类,有x,y两个属性。编写一个PointDemo类,并提供一个distance方法用于计算两点间的距离,实例化两个具体的Point对象。
这里有两种做法,大家可以自行参考。很简单的小题,但是两个做法的思路是不同的。
下面先上Point类
package com.qst.fuxi;
public class Point {
private Double x;
private Double y;
public Point() {
}
public Point(Double x, Double y) {
super();
this.x = x;
this.y = y;
}
public Double getX() {
return x;
}
public void setX(Double x) {
this.x = x;
}
public Double getY() {
return y;
}
public void setY(Double y) {
this.y = y;
}
}
下面开始第一种方法。
package com.qst.fuxi;
import java.util.Scanner;
import java.math.*;
public class PointDemo {
Point p1;
Point p2;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个点的x值x1");
Double x1 = scanner.nextDouble();
System.out.println("请输入第一个点的y值y1");
Double y1 = scanner.nextDouble();
System.out.println("请输入第二个点的x值x2");
Double x2 = scanner.nextDouble();
System.out.println("请输入第二个点的y值y2");
Double y2 = scanner.nextDouble();
Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
PointDemo pd2= new PointDemo(p1,p2);
pd2.distance();
}
public void distance() {
Double a=Math.sqrt(Math.abs(p1.getX()-p2.getX())*Math.abs(p1.getX()-p2.getX())+Math.abs(p1.getY()-p2.getY())*Math.abs(p1.getY()-p2.getY()));
System.out.println(a);
}
public PointDemo() {
super();
}
public PointDemo(Point p1, Point p2) {
super();
this.p1 = p1;
this.p2 = p2;
}
public Point getP1() {
return p1;
}
public void setP1(Point p1) {
this.p1 = p1;
}
public Point getP2() {
return p2;
}
public void setP2(Point p2) {
this.p2 = p2;
}
}
第二种方法,为了方便,我把主方法放在了一起,方便看。
package com.qst.fuxi;
import java.util.Scanner;
public class PointDemo2 {
public Point input() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入横坐标");
Double x = scanner.nextDouble();
System.out.println("请输入纵坐标");
Double y = scanner.nextDouble();
Point point = new Point(x, y);
return point;
}
public double distant(Point p1,Point p2){
double c=0;
double a=Math.pow(p1.getX()-p2.getX(), 2);
double b=Math.pow(p1.getY()-p2.getY(), 2);
c=Math.sqrt(a+b);
return c;
}
public static void main(String[] args) {
PointDemo2 pointDemo=new PointDemo2();
Point []Points=new Point[2];
for (int i = 0; i < Points.length; i++) {
Points[i]=pointDemo.input();
}
System.out.println(pointDemo.distant(Points[0],Points[1]));
}
}
到这里就结束啦。作为入门的小萌新还是要继续学习的!加油!