Search code examples
javaloopsoopreturnreturn-value

How to loop 2 variables while alternating return values


I am just new at coding im not sure if this is even possible in my program i should be able to loop 1 - 2 - 1 - 2 - 1 - 2 alternating but im not sure what to do

what should i put inside this think function so every time i call it, it alternates between 1-2-1-2-1-2

example first time i called it think would return 1 then second time would return 2 then third time would return 1 again

public int think() {
    int i=1;
    int z=1;

    if(i==1){
        return i;

    }
    if(i==2){
        return i;
    }


    return i;
}

The code below is getting the return value of think function

public static String askEnemy(Enemy enemy){
    String x = "null";

    switch (enemy.think()) {
        case 1:
            x = "Hit";
            break;
        case 2:
            x = "Defend";
            break;
        case 3:
            x = "Charge";
            break;

    }


    return x;
} 

Solution

  • The variables i and z are local to the think method and hence they get initialized to the values you have at the start each time they get called. You cannot carry forward state using them.

    You need to have a member variable in the Enemy class for this.

    class Enemy {
     ...
     private int thinkVar = 1;
    
     public int think() {
         int thinkResult = thinkVar;
         thinkVar = (thinkVar == 1) ? 2 : 1;
         return thinkResult;
     } 
    }
    

    EDIT:

    If you could have it as -1 and 1, you can simply write thinkVar = -thinkVar