[英]Getter function not returning value when accessed from another class
I have a class as follows: 我有一个课程如下:
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;
}
}
I have another class 我有另一堂课
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);
}
Lines 2, 4, 5, and 6 are showing values as zero. 第2,4,5和6行显示为零。 Which I don't want to. 我不想这样做。 Below is the logcat image. 下面是logcat图像。
Have I made error in the access Specifiers? 我是否在访问说明符中出错?
It's hard for us to tell what's going on without knowing mSpeedX
and mSpeedY
. 在不了解mSpeedX
和mSpeedY
情况下,我们很难分辨出发生了什么。 Try casting both elapsedTime
and your mSpeedX/Y
variables to floats before doing the math. 在进行数学运算之前,尝试将elapsedTime
和mSpeedX/Y
变量转换为浮点数。 Floating point math is pretty picky in Java. 浮点数学在Java中非常挑剔。 Also ensure that the animate
method is actually being called. 还要确保实际调用animate
方法。
One final note, I probably shouldn't bring this up but it's killing me. 最后一点,我可能不应该提起这件事,但这会让我失望。 You should really, really work on your code consistency and style. 您应该真正地,真正地处理您的代码一致性和风格。 Your naming conventions, newline/sameline brace conventions, and indentation habits are all over the place. 您的命名约定,换行/同线括号约定和缩进习惯都到处都是。 Code readability and maintainability go down dramatically if your programming style is not consistent . 如果编程风格不一致,代码可读性和可维护性会大幅下降。
One more thing: you don't need to call the setter methods after assigning values to a variable. 还有一件事:在为变量赋值之后,不需要调用setter方法。 You've already set the value of the very same variable that your set/get methods are accessing. 您已经设置了set / get方法访问的同一个变量的值。 Good luck! 祝好运!
Element
class in the Panel
class, you never called setter method setmX() and setmY() to set the values. 虽然您在Panel
类中创建了Element
类的对象,但您从未调用setter方法setmX()和setmY()来设置值。 You are directly calling the getter methods which returns you the default values. 您直接调用getter方法,它返回默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.