Creating a Real Countdown in java (Second by Second)

Description:

Yes! This is not your everyday clock-down simulation in java. Back in the past, we created a mediocre countdown simulation: mainly a counter integer in which its value is decreasing using a loop. The one we're going to explore now is a "second by second " countdown.


Code:

package com.javaproblems.countdown;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

import javax.swing.Timer;

public class CountDown {

 private static int counter;
 
 public static void main(String[] args) {
  
  Scanner scan = new Scanner(System.in);
  System.out.println("Please enter the counter value");
  counter  = scan.nextInt();
  
  Timer timer = new Timer(1000, new CountDownListener());

  timer.start();
  while (timer.isRunning()) {
   if(counter == -1) {
    timer.stop();
    break;
   }
  }
  
  
 }
   
  private static class CountDownListener implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent arg0) {
    if(counter>=0) { 
     System.out.println(counter);
     
    if (counter ==0) System.out.println("LiftOff");
    
    counter--;
    }
   
  } 
   
  }
}

No comments:

Post a Comment