[英]Java - What the difference of setXY(x1, y1) and new Object
The problem I'm having is typing x1, x2, y1, y2 into begin and end.我遇到的问题是在开始和结束中输入 x1、x2、y1、y2。 This is what I wrote but it did not run as expected.这是我写的,但它没有按预期运行。
begin.setXY(x1, y1);
end.setXY(x2, y2);
After reading the answers for this exercise, I found that they used these two lines and it worked.在阅读了本练习的答案后,我发现他们使用了这两行并且有效。 I don't know the difference between these lines of code, please help me !!!我不知道这几行代码之间的区别,请帮助我!!! And I'm a beginner in java and don't have much experience if you can give me some tips to learn而且我是java的初学者,如果您能给我一些学习技巧,我没有太多经验
begin = new Point(x1, y1);
end = new Point(x2, y2);
this is my Point class这是我的观点 class
public class Point {
private int x;
private int y;
public Point () {
this.x = 0;
this.y = 0;
}
public Point (int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString () {
return "(" + x + "," + y + ")";
}
public int[] getXY () {
int[] array = new int[2];
array[0] = x;
array[1] = y;
return array;
}
public void setXY (int x, int y) {
this.x = x;
this.y = y;
}
}
and this is my Line class这是我的线 class
public class Line {
private Point begin;
private Point end;
public Line (int x1, int y1, int x2, int y2) {
// begin.setXY(x1, y1);
// end.setXY(x2, y2);
begin = new Point(x1, y1);
end = new Point(x2, y2);
}
}
this is my Main class这是我的主要 class
public class Ex2 {
public static void main(String[] args) {
Line a = new Line(1, 2, 3, 4);
System.out.println(a.getBegin());
System.out.println(a.getEnd());
}
}
Just add the getters and setter in your Line
class and you should start getting the values:只需在 class Line
中添加 getter 和 setter 即可开始获取值:
public class Line {
private Point begin;
private Point end;
public Line (int x1, int y1, int x2, int y2) {
begin = new Point(x1, y1);
end = new Point(x2, y2);
}
// Just add this
public Point getBegin() { return begin; }
public Point getEnd() { return end; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.