【问题标题】:making a simple ball class for moving ball but not moving为移动球但不移动制作一个简单的球类
【发布时间】:2013-10-07 09:59:44
【问题描述】:

我正在制作一个用于移动球的简单程序,但不幸的是它没有移动,当我在运行程序后设置值 x=5 和 y=4 时,它在控制台上显示“Ball @ (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);
}

}

【问题讨论】:

    标签: java class oop


    【解决方案1】:

    您没有任何constructors,因此调用了默认的xy

    为了得到你想要的,你应该提供一个构造函数(你快到了),只需删除 void 修饰符:

    public void Ball()

    现在,这是一个构造函数。请注意,您应该对另一个预期的构造函数执行相同的操作。

    【讨论】:

      【解决方案2】:

      Ball 的构造函数中删除void 关键字以允许为xy 赋值

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

      【讨论】:

      • 构造函数没有返回类型,你拥有的是一个不会被调用的方法
      【解决方案3】:

      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;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-07-24
        • 2017-10-28
        • 2016-02-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多