静态计数(Android)

时间:2014-04-10 05:58:54

标签: java android count

在方法bounce()中,第一个增量中的count值不会被提前到第二个增量。我的意思是使用count=0 ..然后第一次增加计数,它的值变为第二次第二次vaue变为1 ..可能是因为两个计数都存储在不同的内存位置...如果我将计数设为静态,那么每次运行应用程序时它都会保留上次存储的值,这是我不想要的。 .i希望第一个增量中count的值应该被提前到第二个增量...如果我在bounce()方法中循环,我也不能把计数放在外面,因为它会给出wroung输出。我应该怎么做?

public class Ball {

private Point p;               //Represents the x and y position of the Ball
private int c;                 //Represents the color of the Ball
private int r;                 //Represents the Radius of the Ball.
private int dx;                   //Represents the change in x position of the Ball. (Horizontal Speed)
private int dy;               //Represents the change in y position of the Ball. (Vertical Speed)
private Paint paint;           //Android Object holding the color for drawing on the canvas
public int count = 0;
public Ball(int x,int y,int col,int radius)
{

    p=new Point(x,y);
    c=col;
    r=radius;
    paint=new Paint();
    dx=0;
    dy=0;
}
public int getCount()
{return count;
}
public int getX()                       //Returns the x position of the ball as an integer
{return p.x;
}
public int getY()                      //Returns the y position of the ball as an integer
{
    return p.y;
}

public int getRadius()               //Returns the Radius of the ball as an integer
{return r;
}
public Paint getPaint()            //Returns the Paint of the Ball as a Paint Object
{return paint;
}
public void setColor(int col)      //Sets the Color of the Ball
{c=col;
if (paint == null) 
    paint = new Paint();
 paint.setColor(col);
}
public void goTo(int x,int y)       //Sets the x and y positions of the Ball
{p.x=x;
p.y=y;
}
public void setDX(int speed)      //Sets the Horizontal Speed of the Ball
{dx=speed;
}
public void setDY(int speed)       //Sets the Vertical Speed of the Ball
{
    dy=speed;
}
public void move()                 //Changes the x and y position by the dx and dy values
{
    p.x=p.x+dx;
    p.y=p.y+dy;
}
public void setX(int x)
{
    p.x = x;
}
public void setY(int y)
{
    p.y = y;
}
public int getDX()
{
    return p.x;
}
public int getDY()
{
    return p.y;
}
public void bounce(Canvas canvas)       //Bounces off the Sides of the Canvas
{ 
    move();
    if(p.x>canvas.getWidth()|| p.x<0)
    {
        count++;
        dx=dx * -1;
    }
    if(p.y>canvas.getWidth()|| p.y<0)
    {
        count++;
        dy=dy * -1;
    }


    MainActivity.tv.setText(String.valueOf(getCount()));
}
}

2 个答案:

答案 0 :(得分:0)

我想我应该添加我的评论作为答案。您应该只创建Ball类的一个实例并使用它。每次创建Ball的新实例时,都会设置count = 0

答案 1 :(得分:-1)

您应该使用singleton类来维护计数增量,并且每当应用程序启动时将其设置为零。而不是静态制作Singleton类并使用setter和getter方法在该类中维护计数很容易。