我有一个课程如下:
public class Element extends Activity
{
public float mX;
public float mY;
public void animate(long elapsedTime)
{
mX += mSpeedX * (elapsedTime / 20f);
mY += mSpeedY * (elapsedTime / 20f);
setmX(mX);
setmY(mY);
checkBorders();
}
public void setmX(float mX)
{
Log.i("this.mX","mY at setmX read is :"+this.mX ); **//Line 1**
this.mX = mX;
}
public float getmX() {
Log.i("mX","mX in getmX read is :"+mX ); **//Line 2**
return mX;
}
public void setmY(float mY) {
this.mY = mY;
Log.i("this.mY","mY at setmY read is :"+this.mY ); **//Line 3**
}
public float getmY() {
Log.i("mY","mY in getY read is :"+mY ); **//Line 4**
return mY;
}
}
我有另一个班级
public class Panel extends SurfaceView implements SurfaceHolder.Callback
{
int x = 100;
int y = 0;
public float xval;
public float yval;
@Override
public boolean onTouchEvent(MotionEvent event)
{
Element element = new Element();
float x = event.getX();
float y = event.getY();
Log.i("x","x in panel is :"+x);
//toast tos = new toast();
xval = element.getmX();
Log.i("xval","xval in playactivity obtained is :"+xval ); **//Line 5**
yval = element.getmY();
Log.i("yval","yval in playactivity obtained is :"+xval ); **//Line 6**
return super.onTouchEvent(event);
}
第2,4,5和6行显示为零。我不想这样做。下面是logcat图像。
我是否在访问说明符中出错?
答案 0 :(得分:1)
如果不知道mSpeedX
和mSpeedY
,我们很难说出发生了什么。在进行数学运算之前,请尝试将elapsedTime
和mSpeedX/Y
变量转换为浮点数。浮点数学在Java中非常挑剔。还要确保实际调用animate
方法。
最后一点,我可能不应该提起这件事,但是这让我很伤心。您应该真的,非常处理您的代码一致性和样式。您的命名约定,换行/同线括号约定和缩进习惯都到处都是。如果您的编程风格不是一致,则代码可读性和可维护性会大幅下降。
还有一件事:在为变量赋值后,不需要调用setter方法。您已经设置了set / get方法访问的同一个变量的值。祝你好运!
答案 1 :(得分:1)
Element
类中创建了Panel
类的对象,但您从未调用setter方法setmX()和setmY()来设置值。您正在直接调用getter方法,该方法返回默认值。