-1

I'm developing an app with a bird flying randomly, the number of times you tap the bird is your score which is saved as 'hitCount'. I'm trying to figure out how to return 'hitCount' in a new method 'getHitCount' in the same class

KayzMark
  • 3
  • 1
  • 5

1 Answers1

2

You probably have a problem with variable scope. Let's say you have a class called "bird"; you will want to save all important variables not in a method or a constructor, but as an instance variable. When you instantiate your "bird" class, assign the value 0 to the hitCount instance variable in the constructor. Then, you want to have 2 methods, a setter and a getter, for that variable. One would be a void method called "setHitCount" (like regular setters) which you can set the value of hitCount, and make the other one a method that returns the type int (or whatever type you make "hitCount", like regular getters), and simply put the instance variable "hitCount" as the return value. And now you can get the hitCount from whatever holds a reference to your bird object.

Read up on Encapsulation, how you manage data in your classes.

Here is a sample of the class:

public class bird {

    private int hitCount;

    public bird(){
        //instantiates the bird, set initial values here
        hitCount = 0;
    }

    public void setHitCount(int hitCount){
        //pass in a number as parameter to set your instance var hitCount
        this.hitCount = hitCount;
    }

    public int getHitCount(){
        //returns the value of your instance variable
        return hitCount;
    }
}
Community
  • 1
  • 1
Preston Garno
  • 1,175
  • 10
  • 33