I want a loop that can count back and forth from 0 to 3. At first it counts up 1 each time and then when it reaches 3, it will count backwards to 0, then back up to 3 and so on. I already have a runnable that makes it count automatically.

Here is the code:

moveInt++;
		animateInt++;
		if(animateInt==20){
			if(!max){
			badGuyInt +=1; //count up 1
			}
			if(max){
				badGuyInt -=1; //count back 1
			}
			animateInt=0;
			
			if(badGuyInt==3){ //When it reaches 3, it will start to count down.
				badGuyInt=0;
				max = true;
			}
			if(badGuyInt==0){// When it reaches 0, it counts up.
				max = false;
			}
		}

The way it's written now, it just goes back to 2 when it reaches 3 then back to 3, and back to 2 and so on. I want it to go all the way back to 0 before it starts to count up again.

Edited 5 Years Ago by SolidSora: n/a

Just have a flag which may call goUp. Then switch it when it hits your top or bottom value.

boolean goUp = true;
int cnt = 0;
for (int i=0; i<18; i++) {
  if (goUp) { cnt++; }
  else { cnt--; }
  System.out.println(cnt);
  if (cnt==3) { goUp = false; }
  if (cnt==0) { goUp = true; }
}

Edited 5 Years Ago by Taywin: n/a

You can simplify Taywin's method by starting your flag at 1, and multiplying by -1 at each boundary. Then just add the flag to the current total, and you've eliminated the middle if.

You can do simplify further by just counting and then flipping.

public static void main(String[] args)
   {


   int i = 0;
   int j = 1;
   while (true)
   {
      do{
         System.out.println(i);
         i+=j;
      } while (i%3 != 0);
      j*=-1;
   }

   }

EDIT: of course now I'm sitting here trying to eliminate that inner while clause, to simplify even further. I'm sure it'll come to me.

Edited 5 Years Ago by jon.kiparsky: afterthought

Trivial solution:

public static void main(String[] args)
   {

   int[] array = {0,1,2,3,2,1};
   int i = 0;
   while (true)
   {
      
         System.out.println(array[i]);
      i = ++i%6;
   }
}

Okay, it's not really counting. That means... it doesn't count. Sorry.

This article has been dead for over six months. Start a new discussion instead.