我在 java 中完成了一项作业,我有两个类,需要计算 x 和 y 位置。我得到了一半的测试正确,但似乎无法让最后两个测试正确。你能不能指导我朝着正确的方向发展?我有一个类 calle Point 和一个 PointMain。我在 PointMain 中获取参数,需要在 Point 中创建正确的方法。我无法在 PointMain 类中进行任何更改,因为我是从作业中得到的。
类点:
public class Point {
private int x = 0;
private int y = 0;
public Point() {
}
public Point(int xPoint, int yPoint) {
x = xPoint;
y = yPoint;
}
public String toString() {
return x + "," + y;
}
public double distanceTo(Point p2) {
double avstand = Math.sqrt(((p2.x*1 - p2.x*2) * (p2.x*1 - p2.x*2)) + ((p2.y*1 - p2.y*2) * (p2.y*1 - p2.y*2)));
return avstand;
}
public void move(int iPoint, int jPoint) {
x = x + iPoint; // I have a problem with this that it doesn't add
y = y + jPoint; // the 3,4 that I got from p2 with the 5,-2.
}
public void moveToXY(int xTag, int yTag) {
}
public boolean isEqualTo(Point p2) { //And I'm not really sure on how to
return false; //construct this method either...
}
}
类点Main:
public class PointMain {
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point(3,4);
System.out.println(p1.toString()); // ==> (0,0)
System.out.println(p2.toString()); // ==> (3,4)
if (p1.isEqualTo(p2)) // False!
System.out.println("The two points are equal");
double dist = p1.distanceTo(p2);
System.out.println("Point Distance: "+dist);
p2.move(5,-2); // ==> (8,2)
p1.moveToXY(8,2); // ==> (8,2)
System.out.println(p1);
System.out.println(p2);
if (p1.isEqualTo(p2)) // True!
System.out.println("The two points are equal");
}
}
首先你应该添加吸气剂
public int getX()
{
return x;
}
public int getY()
{
return y;
}
比执行 isEqual
public boolean isEqualTo(Point p2) {
return x == p2.getX() && y == p2.getY();
}
您还可以将 x 和 y 声明为 public,然后就不需要 getter 并且代码更简单,正如您在 java.awt.Point 的实现中所见。我没有看到“移动”功能的问题。最后
public void moveToXY(int xTag, int yTag) {
x = xTag;
y = yTag;
}
有关其他信息,您可以查找 java.awt.Point 的实现方式,并处理命名 iPoint/jPoint 的函数参数是可怕的名称
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句