我是Java新手,我收到一个作业,要求我编写一个名为PointerTester
的类,它有两个Point作为实例变量。我需要在坐标(0.0,0.0)和一个在(10.0,12.0)初始化其中一个。然后我需要将每个点移动x中的+2.0和Y中的-3.0,查询点的坐标,并打印出值。
到目前为止,我有这个:
public class PointerTester{
/*instance variables*/
private double pointOneX;
private double pointOneY;
private double pointTwoX;
private double pointTwoY;
private double deltaX;
private double deltaY;
/*constructor to initialize*/
public PointerTester (){
pointOneX = 0.0;
pointOneY = 0.0;
pointTwoX = 10.0;
pointTwoY = 12.0;
deltaX = 2.0;
deltaY = -3.0;
}
/*constructor to initialize to specific value*/
PointerTester(double pointOneX, double pointOneY, double pointTwoX, double pointTwoY){
this.pointOneX = pointOneX;
this.pointOneY = pointOneY;
this.pointTwoX = pointTwoX;
this.pointTwoY = pointTwoY;
}
/*command to change value*/
public void moveBy(double deltaX, double deltaY){
this.pointOneX = this.pointOneX + deltaX;
this.pointOneY = this.pointOneY + deltaY;
this.pointTwoX = this.pointTwoX + deltaX;
this.pointTwoY = this.pointTwoY + deltaY;
}
/*Queries*/
public double getOneX(){
return pointOneX;
}
public double getOneY(){
return pointOneY;
}
public double getTwoX(){
return pointTwoX;
}
public double getTwoY(){
return pointTwoY;
}
/*print values*/
public static void main(String[] args){
PointerTester pointOne = new PointerTester();
PointerTester pointTwo = new PointerTester();
System.out.println("Point One after move (" + pointOne + ")");
System.out.println("Point Two after move (" + pointTwo + ")");
}
}
我无法弄清楚如何正确输出值,或者我是否完全错误地解决了这个问题。
编辑我似乎需要使用我最初认为应该是独立的代码
public class Point{
public double x;
public double y;
public Point(double x, double y){
this.x = x;
this.y = y;
}
public void setX(double x){
this.x = x;
}
public void setY(double y){
this.y = y;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
}
如何将其合并到我的代码中?
答案 0 :(得分:3)
我认为开始时你应该有一个名为“Point”的单独的类,它封装了一个X和Y值,并包含一个“moveBy”方法。它还可以实现“toString()”,这样“System.out.println”将为它打印一些不错的东西。 [编辑:或者只使用java.awt.Point。]
除此之外,我会把它留给你作为你的功课。
答案 1 :(得分:1)
您可能想要使用一些Point对象。
Point p1 = new Point(); 点p2 =新点(10,12);
然后,您可以使用点类中的setLocation或translate方法。也许整件事看起来像这样?希望这会有所帮助。
main(){
//make some points
Point p1 = new Point();
Point p2 = new Point(10,12);
//move our points
p1.translate(2,-3);
p2.translate(2,-3);
//print our points
System.out.println(p1);
System.out.println(p2);
}
答案 2 :(得分:0)
您可以实现toString方法。这里有一些例子: http://www.javapractices.com/topic/TopicAction.do?Id=55
答案 3 :(得分:0)
您正在尝试打印PointerTester对象而不是其中包含的值。 System.out.println(pointOne.getOneX())至少应该停止抛出异常并允许您正确打印。