I suddenly remembered Google's 15-minute rule I tried to see if it can be described as a timer in java
I haven't come up with the refreshing introduction to Java that I'm currently reading, so I'd like to see the API or refer to Qiita. It's been about 2 weeks since I started learning java, so I tried splitting the code
Main
import java.util.*;
public class Main {
static Scanner inp = new Scanner(System.in);
public static void main(String[] args) {
try {
System.out.print("Let's set up a bomb timer(sec): ");
int sec = inp.nextInt();
BombTimer.Bomb(sec);
} catch (InputMismatchException e) {
System.out.println("The input is incorrect.");
} finally {
inp.close();
}
}
}
BombTimer
import java.util.*;
public class BombTimer {
public static void Bomb(int sec) {
System.out.println("Until the explosion" + sec + "Seconds");
Timer timer = new Timer();
TimerTask task = new TimerTask() {
int secCount = sec - 1;
@Override
public void run() {
if (secCount > 0) {
if (secCount <= 60 && secCount % 10 == 0) {
System.out.println("remaining" + secCount + "Seconds");
} else if (secCount == 5) {
System.out.println(secCount + "Seconds ago");
} else {
System.out.println(sec);
}
} else {
System.out.println("Doka --------");
System.exit(0);
}
secCount --;
}
};
timer.sucheduleAtFixedRate(task, 1000, 1000);
}
}
The execution result is as follows
result
Set up a bomb timer(sec): 13
13 seconds left until the explosion
12
11
10 seconds left
9
8
7
6
5 seconds ago
4
3
2
1
Doka --------!
What I learned this time -@Override is a description --Scanner close () --You can understand how to use it by looking at the API reference.
[Java] Timer processing implementation method
I've figured it out, but I still don't know the correct answer. Should it be an if statement or a switch statement? Is exception handling mandatory? I have no end to my doubts. .. ..
Please do not hesitate to point out any points you notice.
Recommended Posts