Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a countdown timer in Java [closed]

Tags:

java

countdown

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:


  • dynamic input for the time (set time)
  • countdown from input time to 0
  • when o => jump out of loop

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.

like image 510
Vamala Avatar asked Jan 18 '13 06:01

Vamala


People also ask

How do you keep a Countdowntimer running even if the app is closed?

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.

How does timer in Java work?

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.

How do you use a countdown timer?

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.


2 Answers

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.

like image 77
Achintya Jha Avatar answered Oct 09 '22 07:10

Achintya Jha


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.

like image 27
Zach Latta Avatar answered Oct 09 '22 06:10

Zach Latta