This program is designed to determine whether a given number is odd or even.
Understanding whether a number is odd or even is a fundamental concept in mathematics
and programming. An even number is any integer that is exactly divisible by 2, while an
odd number is an integer that is not divisible by 2. This simple program helps users
input a number and receive immediate feedback on its classification.
Objective
The objective of this program is to provide a clear and straightforward method for
users to input a number and receive a response indicating whether the number is odd or
even. This program can serve as an introductory exercise in programming for beginners.
Java Code
import java.util.Scanner;
public class OddEvenChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is an odd number.");
}
scanner.close();
}
}
Program Structure and Explanation
The program consists of the following key components:
- Import Statement: The program imports the
Scanner
class from thejava.util
package, which allows for user input. - Main Class: The class is named
OddEvenChecker
, which contains the main method where the program execution begins. - Scanner Initialization: An instance of
Scanner
is created to read input from the user. - User Input: The program prompts the user to enter a number and stores it in the variable
number
. - Condition Check: Using an if-else statement, the program checks if the number is divisible by 2. If it is, it prints that the number is even; otherwise, it states that the number is odd.
- Scanner Closure: The scanner is closed to prevent resource leaks.
How to Run the Program
- Ensure you have Java Development Kit (JDK) installed on your computer.
- Open a text editor or Integrated Development Environment (IDE) such as Eclipse or IntelliJ IDEA.
- Copy and paste the provided Java code into a new file and save it as
OddEvenChecker.java
. - Open a terminal or command prompt and navigate to the directory where you saved the file.
- Compile the program by running the command:
javac OddEvenChecker.java
. - Run the compiled program using the command:
java OddEvenChecker
. - Follow the prompt to enter a number and observe the output indicating whether it is odd or even.