制作一个简单的球类用于移动球但不移动

时间:2013-10-07 09:59:45

标签: java class oop

我正在制作一个简单的移动球程序,但不幸的是它没有移动,当我在运行程序后将值x = 5和y = 4时显示&#34 ;球@(0.0,0.0)"在控制台上请帮助我的错误。

public class Ball
{
    private double x,y; //private variables...

//creating constructors..
public void Ball(double x, double y)
{
    this.x=x;
    this.y=y;
}
public void Ball()
{
    x=5.0;
    y=4.0;
}
//getter and setter for private variables....
public double getX()
{
    return x;
}
public void setX()
{
    this.x=x;
}
public double getY()
{
    return y;
}
public void setY()
{
    this.y=y;
}
public void setXY(double x, double y)
{
    this.x=x;
    this.y=y;
}
public void move(double Xdisp, double Ydisp)
{
    x+=Xdisp;
    y+=Xdisp;
}
public String toString()
{
    return "Ball @ ("+x+","+y+")";
}
public static void main(String[] args)
{
    Ball b=new Ball();
    System.out.println(b);
}

}

3 个答案:

答案 0 :(得分:1)

void的构造函数中移除Ball关键字,以允许xy分配值

public Ball() {
    x = 5.0;
    y = 4.0;
}

答案 1 :(得分:1)

您没有constructors,因此会调用默认值xy

为了拥有你想要的东西,你应该提供一个构造函数(你几乎就在那里),只需删除void修饰符:

public void Ball()

现在,这是一个构造函数。请注意,您应该为其他意图构造函数执行相同的操作。

答案 2 :(得分:0)

public void Ball()必须是构造函数。

public Ball()
{
    x=5.0;
    y=4.0;
}

但你已经写了一种方法。 set方法中也没有参数,必须像

public void setX(double x)
{
    this.x=x;
}
public void setY(double y)
{
    this.y=y;
}