forked from TimSongCoder/LearnJavaForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackAndForth.java
More file actions
55 lines (47 loc) · 1.13 KB
/
Copy pathBackAndForth.java
File metadata and controls
55 lines (47 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.Timer;
import java.util.TimerTask;
/**
* Repeatedly move an asterisk forward 20 steps and then backward 20 steps.
*/
public class BackAndForth{
private static final long INTERVAL = 500;
private static final String TOKEN = "*";
private static int MAX_STEP = 20;
private static volatile int stepCount = 0;
private static volatile boolean isForward = true;
public static void main(String[] args){
Timer timer = new Timer();
TimerTask task = new TimerTask(){
@Override
public void run(){
StringBuilder sb = new StringBuilder(TOKEN);
for(int i=0; i<stepCount; i++){
sb.insert(0, " ");
}
System.out.println(sb.toString());
if(isForward){
stepCount++;
}else{
stepCount--;
}
if(stepCount == MAX_STEP){
isForward = false;
}else if(stepCount == 0){
isForward = true;
}
}
};
long interval = -1;
if(args.length!=0){
try{
interval = Long.parseLong(args[0]);
}catch(NumberFormatException nfe){
nfe.printStackTrace();
}
}
if(interval < 0){
interval = INTERVAL;
}
timer.schedule(task, 1000, interval);
}
}