I'm a beginner (student) in programming and was assigned to create a game. The game I'm making is called boggle. In which the player have to find words in a random letter board within a given time, but I'm having trouble with creating the timer. This is what it my timer should do:
All I need to know is how to make it countdown. I don't think I need a ActionListener because it starts ticking the moment the class is created.
Any help, advice, links, push in the right direction will be accepted with open arms.
To keep the timer running while the app is closed, you need to use a service. Listen to the broadcast of the service in the activity. See this SO answer to learn whether registering the receiver in onCreate, onStart, or onResume is right for you.
A Timer in Java is a process that enables threads to schedule tasks for later execution. Scheduling is done by keeping a specific process in the queue such that when the execution time comes, the processor can suspend other processes and run the task.
In one EditText, the user can put a number as minutes and in another EditText, a number as seconds. After clicking the finish button, the seconds EditText should start to countdown and update its text every second.
import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; public class Stopwatch { static int interval; static Timer timer; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input seconds => : "); String secs = sc.nextLine(); int delay = 1000; int period = 1000; timer = new Timer(); interval = Integer.parseInt(secs); System.out.println(secs); timer.scheduleAtFixedRate(new TimerTask() { public void run() { System.out.println(setInterval()); } }, delay, period); } private static final int setInterval() { if (interval == 1) timer.cancel(); return --interval; } }
Try this.
You'll see people using the Timer class to do this. Unfortunately, it isn't always accurate. Your best bet is to get the system time when the user enters input, calculate a target system time, and check if the system time has exceeded the target system time. If it has, then break out of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With