Home > Software engineering >  How to check if a variable is set to a particular value for the first time in Android Studio?
How to check if a variable is set to a particular value for the first time in Android Studio?

Time:10-06

I'm trying to implement a level-up type of thing. So, I wanted to check whenever the "mLevel" variable is changed for the first time. For instance, 1 to 2, or 2 to 3 for the very first time.

public class UserModel {
    private static int mExperience;
    private static int mLevel;

    public int getExperience() {
        return mExperience;
    }

    public void setExperience(int experience) {
        mExperience = experience;
    }

    public int getLevel() {
        return mLevel;
    }

    public void setLevel(int experience) {
        if(experience < 80){
            mLevel = 1;
        }else if(experience >= 80 && experience <270){
            mLevel = 2;
        }else if(experience >= 270 && experience <640){
            mLevel = 3;
        } else if(experience >= 640 && experience <1250){
            mLevel = 4;
        }else if(experience >= 1250 && experience <2160){
            mLevel = 5;
        }else if(experience >= 2160 && experience <3430){
            mLevel = 6;
        }else if(experience >= 3430 && experience <5120){
            mLevel = 7;
        }else if(experience >= 5120 && experience <7290){
            mLevel = 8;
        }else if(experience >= 7290 && experience <10000){
            mLevel = 9;
        }else{
            mLevel = 10;
        }
    }
}

CodePudding user response:

I added a variable named "hLevel" and added an if check, which checks if hLevel is lower than mLevel. If this is the case, it updates the variable to mLevel and you can do your stuff or call a method in that if case.

 public class UserModel {
private static int mExperience;
private static int mLevel;
private static int hLevel

public int getExperience() {
    return mExperience;
}

public void setExperience(int experience) {
    mExperience = experience;
}

public int getLevel() {
    return mLevel;
}

public void setLevel(int experience) {
    if(experience < 80){
        mLevel = 1;
    }else if(experience >= 80 && experience <270){
        mLevel = 2;
    }else if(experience >= 270 && experience <640){
        mLevel = 3;
    } else if(experience >= 640 && experience <1250){
        mLevel = 4;
    }else if(experience >= 1250 && experience <2160){
        mLevel = 5;
    }else if(experience >= 2160 && experience <3430){
        mLevel = 6;
    }else if(experience >= 3430 && experience <5120){
        mLevel = 7;
    }else if(experience >= 5120 && experience <7290){
        mLevel = 8;
    }else if(experience >= 7290 && experience <10000){
        mLevel = 9;
    }else{
        mLevel = 10;
    }
    if (hLevel<mLevel) {
        //Current highest
        hLevel = mLevel;
    }
}
}
  • Related