This Java code example demonstrates how to determine whether a given integer is even or odd. The program prompts the user to enter a value, checks if the number is even or odd using the modulus operator, and then prints the result.
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int x;
System.out.print("Enter a value for x: ");
x = reader.nextInt();
reader.close();
if (x % 2 == 0) {
System.out.print("Number " + x + " is even");
} else {
System.out.print("Number " + x + " is odd");
}
}
}
class EvenOrOdd
The class EvenOrOdd
contains the main method to execute the program.
class EvenOrOdd {
// class contents
}
public static void main(String[] args)
The main method executes the program and contains the logic for determining if a number is even or odd.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int x;
System.out.print("Enter a value for x: ");
x = reader.nextInt();
reader.close();
if (x % 2 == 0) {
System.out.print("Number " + x + " is even");
} else {
System.out.print("Number " + x + " is odd");
}
}
Scanner reader = new Scanner(System.in);
creates a Scanner
object to read input from the user.int x;
declares a variable to store the input value.System.out.print("Enter a value for x: ");
prompts the user to enter a value.x = reader.nextInt();
reads the integer input and assigns it to the variable x
.reader.close();
closes the Scanner
object to free up resources.if (x % 2 == 0) {
checks if the number is even by using the modulus operator %
to see if there is no remainder when x
is divided by 2.System.out.print("Number " + x + " is even");
prints that the number is even if the condition is true.} else {
handles the case where the number is odd.System.out.print("Number " + x + " is odd");
prints that the number is odd if the condition is false.