【发布时间】:2014-05-07 04:00:45
【问题描述】:
好的,所以我为这个坐标类创建了一个 toString() 方法,但是当我尝试使用 system.out.print() 打印坐标时,它似乎忽略了我的方法,只使用了 Object.toString( ) 方法,并且只返回一个内存地址。
这是我的 toString 方法的代码:
package spacetable;
public class Coordinate {
private int x;
private int y;
public Coordinate(){
x=0;
y=0;
}
public Coordinate(int x, int y){
this.x = x;
this.y = y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public double distTo(Coordinate xy){
double run = xy.getX() - this.getX();
double rise = xy.getY() - this.getX();
double dist = sqrt(run*run + rise*rise);
return dist;
}
public double distTo(int x, int y){
double run = x - this.getX();
double rise = y - this.getX();
double dist = sqrt(run*run + rise*rise);
return dist;
}
@Override
public String toString(){
String Strx = Integer.toString(x);
String Stry = Integer.toString(y);
String result = "(" Strx + ", " + Stry + ")";
return result;
}
}
以及我尝试打印的代码:
package spacetable;
public class CordinateTest {
public static void main(String[] args) {
Coordinate place = new Coordinate(2,3);
System.out.println(place);
}
}
输出是: spacetable.Coordinate@e53108
为什么我的 toString() 被忽略了?
【问题讨论】:
-
你能给出一个简短但完整的例子来说明这个问题吗?您已经几乎做到了,但还没有到我们可以轻松重现问题的阶段。
-
你不应该做 place.toString() 吗?
-
您的代码(修复了语法错误并猜测了
Coordinate构造函数)对我来说很好。您需要显示更多代码让我们弄清楚发生了什么。 -
@Sujan 不,
toString()在这种情况下会被自动调用。 -
你确定这是你的编译代码吗?
标签: java overriding tostring