我正在尝试创建一个函数,该函数使用类型为BasicAsteroid的(x,y,velocity x,velocity y)值生成随机小行星,这是创建随机小行星的构造函数和函数:
private double x, y;
private double vx, vy;
public BasicAsteroid(double x, double y, double vx, double vy) {
this.x = x;
this.x = y;
this.vx = vx;
this.vy = vy;
}
public static BasicAsteroid makeRandomAsteroid() {
Random rand = new Random();
BasicAsteroid x = new BasicAsteroid((rand.nextInt()%FRAME_WIDTH), (rand.nextInt()%FRAME_HEIGHT), (rand.nextInt()%MAX_SPEED), (rand.nextInt()%MAX_SPEED));
System.out.println(x);
return x;
}
然而,这是我创建小行星时的输出:
game1.BasicAsteroid@6773120a
game1.BasicAsteroid@4261b6b3
game1.BasicAsteroid@2673b915
game1.BasicAsteroid@113eb90b
game1.BasicAsteroid@1abcc522
如何输出值而不是类@hashcode? p>
感谢。
答案 0 :(得分:5)
覆盖toString()
方法
@Override
public String toString(){
return "Asteroid at "+x+" "+y+" velocity "+vx+" "+vy;
}
答案 1 :(得分:0)
您需要在类上覆盖方法toString()。
@Override
public String toString(){
return "x: "+this.x+"y: "+this.y+"vx: "+this.vx+"vy: "+this.vy
}
答案 2 :(得分:0)
在java中,当您打印对象时,会调用其toString()方法来创建将要打印的字符串。你在这里看到的是默认toString方法的输出。如果要很好地打印值,请添加如下函数:
@Override
String toString(){
return "Asteroid with coords: (" + x + ", " + y + "), velocity: (" + vx + ", " + vy + ")";
}