Java 使用 Point 类的示例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18951124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
An example of the use of the Point class?
提问by Jake Burch
I'm trying to use Point(double x, double y), getX(), getY()
to create a point and return it with toString()
. I can't find an example of how to do this anywhere.
我正在尝试使用Point(double x, double y), getX(), getY()
创建一个点并将其返回toString()
。我在任何地方都找不到如何执行此操作的示例。
public class Point {
private final double x;
private final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() {
return ("(" + x + "," + y + ")");
}
}
采纳答案by William Gaul
You might want to do this instead:
你可能想要这样做:
public Point(double x, double y) {
this.x = x;
this.y = y;
}
Then...
然后...
System.out.println(new Point(5.0, 5.0).toString());
I don't know why you're setting the this.x and this.y values to 1 in your constructor. You should be setting them to the provided values of x and y.
我不知道为什么要在构造函数中将 this.x 和 this.y 值设置为 1。您应该将它们设置为提供的 x 和 y 值。
You also don't need the outer set of parentheses in the toString()
method. return "(" + x + "," + y + ")";
will work fine.
您也不需要方法中的外部括号集toString()
。return "(" + x + "," + y + ")";
会正常工作。
回答by Nico
I think you look for that:
我认为你在寻找:
public class Point {
private double x;
private double y;
public Point(double x, double y){
this.x=x;
this.y=y;
}public String toString(){
return "("+ this.x+","+this.y+")";
}
public static void main(String[] args){
Point point= new Point(3,2);
System.out.println(point.tostring());
}
}
to had getX() getY() just have to create them.
要让 getX() getY() 只需要创建它们。