Reputation: 91
For this code to run as intended use your cmd/terminal not an IDE. (or you will not see the correct effect of \r)
When the 9 in the terminal reaches the right most position after 4 spaces it will turn around and move back 4 spaces and on and on. However when it reaches the start point after a full cycle there is a remaining 9 on the second space that is not cleared by \r. What could be causing this?
public class Core {
public static void main(String[] args) throws InterruptedException {
int Array[][] = new int[4][6];
int score;
boolean enemy = true;
boolean dir = true;
// EnemyLine
while (enemy) {
for (int i = 1;;) {
Thread.sleep(1000);
if (i == 1)
dir = true;
else if (i == 4)
dir = false;
if (dir == true) {
int a = Array[0][i] = 9;
System.out.printf("%" + i + "d", a);
i++;
System.out.print("\r");
continue;
} else if (dir == false) {
int a = Array[0][i] = 9;
System.out.printf("%" + i + "d", a);
i--;
System.out.print(" \r");
continue;
}
}
}
}
}
Upvotes: 3
Views: 141
Reputation: 1727
Explaining why you are getting such result
Basically in your loop you are changing where to place carriage return \r.
After loop completion when you come back to i = 1. your are changing after how many characters you are going to do a carriage return.
1 -> _9\r
2 -> __9\r
3 -> ___9\r
4 -> ____9 \r
x3 -> ___9 \r
x2 -> __9 \r
x1 -> _9\r
thus the last statement does not clear the 9 at x2
Change needed in if (dir == true)
System.out.print(" \r" ); // enter a space before \r
or it would be best to use
System.out.print(" \r" ); // preferable
you can also remove your sysout \r from the condition loop and use it before your Thread sleep
System.out.print(" \r" );
Thread.sleep(1000);
Upvotes: 3