Introduction:
A countdown timer is a tool that counts down from a specified number of seconds, displaying the remaining time at regular intervals. It can be useful in various applications, such as for alarm clocks, event countdowns, or even as part of a timed quiz. In this tutorial, we will create a simple countdown timer in Java that counts down from a given number of seconds and prints the remaining time every second until the countdown reaches zero.
Objective:
The objective of this project is to develop a simple countdown timer in Java that will:
- Take an input of a starting number of seconds.
- Display the remaining time at each second interval.
- Notify the user when the countdown reaches zero.
Code:
import java.util.Scanner; public class CountdownTimer { public static void main(String[] args) { // Create a scanner object to read input from the user Scanner scanner = new Scanner(System.in); // Ask the user to input the number of seconds for the countdown System.out.print("Enter the number of seconds to countdown from: "); int seconds = scanner.nextInt(); // Start the countdown while (seconds >= 0) { // Print the current number of seconds System.out.println("Time left: " + seconds + " seconds"); // Pause the program for 1 second before continuing try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("An error occurred while waiting."); } // Decrease the seconds by 1 seconds--; } // Notify the user that the countdown is finished System.out.println("Time's up!"); // Close the scanner to prevent resource leak scanner.close(); } }
Explanation of the Program:
This Java program performs the following steps:
- The program starts by asking the user to enter a number of seconds for the countdown.
- It then enters a while loop that continues as long as the number of seconds is greater than or equal to zero.
- Inside the loop, the program prints the current number of seconds left, pauses for one second (using
Thread.sleep(1000);
), and then decreases the countdown by one second. - When the countdown reaches zero, the program prints “Time’s up!” and ends.
How to Run the Program:
-
- Ensure you have Java installed on your computer. If not, you can download it from the official Java website.
- Create a new file with a
.java
extension, for example,CountdownTimer.java
. - Copy the provided code into your Java file.
- Open a terminal or command prompt, navigate to the directory where your Java file is located, and compile the program using the following command:
javac CountdownTimer.java
-
- Once the program is compiled, run it using the following command:
java CountdownTimer
- The program will prompt you to enter the number of seconds to countdown from. Enter any integer, and the countdown will begin!