Variable Will Not Update (Inside If Statement)

1.1k views Asked by At

Working on a school project where we're supposed to modify a game to become educational. I want to cycle through numbers 0, 1, and 2 through the variable moduleThree. But the variable will not update when I set it equal to something else than what I originally defined it as, and it's incredibly frustrating.

I tried putting the if/else chain into a different method with return, but that didn't work. I tried putting it in multiple spots.

public class Alien extends Actor
{
    int SPEED = -7; // Speed of 10 in left direction "-"
    int tempType = (int)(Math.random() * ((2-0) + 1));
    int controlType = 0;
    int moduleThree = 0;

    public Alien() {

    }

    public void act() {
       move (SPEED);
       int timer = 10;
       if (timer>0){
           timer--;
           if(timer == 0) {
               timer = 10;
               controlType++;
               moduleThree = controlType % 3;
               if(moduleThree == 0){
                  ((SpaceLand)(getWorld())).pos.swap("bee");
               }
               else if(moduleThree  == 1){
                  ((SpaceLand)(getWorld())).pos.swap("alien");
               }
               else if(moduleThree  == 2){
                  ((SpaceLand)(getWorld())).pos.swap("soldier");
               }
           }
       }

moduleThree should cycle through 0, 1, and 2 as it calculated controlType % 3, but no update occurs. Even when I manually set it to something like 4, nothing happens. Extremely annoying.

1

There are 1 answers

0
Neil Brown On

The int timer = 10; line is declaring a local variable, so timer is always set to 10 at the beginning of each act() call and the variable is forgotten after each call. It looks like you meant to declare timer as a field of the class to keep its value between act calls. If you move the definition to beneath where moduleThree is declared, I think it will do what you intended.