Java - countdown timer without GUI

I basically make a text β€œgame” (not so much a game as a way to improve basic Java skills and logic). However, as part of this, I want to have a timer. It would count on the time I want from a variable to 0. Now I have seen several ways to do this with gui, however, is there a way to do this without gui / jframe, etc.

So, I'm curious. Can you make a count from x to 0 without using gui / jframe. If so, how would you do it?

Thank you when I get some ideas with progress.

Edit

// Start timer Runnable r = new TimerEg(gameLength); new Thread(r).start(); 

Above, as I call the thread / timer

 public static void main(int count) { 

If I have it in the TimerEg class, the timer matches. However, when compiling the main in another thread, I get.

Error

Now, I completely missed the thread and how will it work? Or am I missing something?

Error:

 constructor TimerEg in class TimerEg cannot be applied to given types; required: no arguments; found int; reason: actual and formal arguments differ in length 

Found in line Runnable r = new TimerEg(gameLength);

+6
source share
3 answers

As with the GUI, you should use a timer, but instead of using a Swing timer, you should use java.util.Timer. See the Timer API for more details. Also look at the TimerTask API , as you will use it in conjunction with your timer.

For instance:

 import java.util.Timer; import java.util.TimerTask; public class TimerEg { private static TimerTask myTask = null; public static void main(String[] args) { Timer timer = new Timer("My Timer", false); int count = 10; myTask = new MyTimerTask(count, new Runnable() { public void run() { System.exit(0); } }); long delay = 1000L; timer.scheduleAtFixedRate(myTask, delay, delay); } } class MyTimerTask extends TimerTask { private int count; private Runnable doWhenDone; public MyTimerTask(int count, Runnable doWhenDone) { this.count = count; this.doWhenDone = doWhenDone; } @Override public void run() { count--; System.out.println("Count is: " + count); if (count == 0) { cancel(); doWhenDone.run(); } } } 
+9
source

You can write your own countdown timer in the same way as:

 public class CountDown { //Counts down from x to 0 in approximately //(little more than) s * x seconds. static void countDown(int x, int s) { while (x > 0 ) { System.out.println("x = " + x); try { Thread.sleep(s*1000); } catch (Exception e) {} x--; } } public static void main(String[] args) { countDown(5, 1); } } 

Or you can use the Java Timer API

+5
source

Simple countdown using java ..

  int minute=10,second=60; // 10 min countdown int delay = 1000; //milliseconds ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { second--; // do something with second and minute. put them where you want. if (second==0) { second=59; minute--; if (minute<0) { minute=9; } } } }; new Timer(delay, taskPerformer).start(); 
0
source

Source: https://habr.com/ru/post/926063/


All Articles