Combine Even and Odd Checks
In the previous steps, we learned how to use the modulo operator to check if a number is odd or even. Our current program already handles both cases using an if-else
statement.
In this step, we will review the code and ensure we understand how the if-else
structure effectively combines the checks for both even and odd numbers.
Recall the code we used in the previous step:
import java.util.Scanner;
public class HelloJava {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
// Check if the number is odd using the modulo operator
if (number % 2 != 0) {
System.out.println(number + " is an odd number.");
} else {
System.out.println(number + " is an even number.");
}
scanner.close();
}
}
Let's break down the logic again:
- The condition
number % 2 != 0
checks if the remainder when number
is divided by 2 is not equal to 0.
- If this condition is
true
, it means the number is odd, and the code inside the if
block is executed: System.out.println(number + " is an odd number.");
.
- If the condition
number % 2 != 0
is false
, it means the remainder is equal to 0. In this case, the number must be even, and the code inside the else
block is executed: System.out.println(number + " is an even number.");
.
This if-else
structure is a very common way to handle two mutually exclusive possibilities (either a number is odd or it's even). We don't need a separate check for even numbers because if a number is not odd, it must be even (for integers).
To complete this step, simply ensure your HelloJava.java
file contains the correct code as shown above.
-
Open the HelloJava.java
file in the WebIDE editor.
-
Verify that the code matches the example provided above, including the import
, Scanner
usage, the prompt, reading the integer, the if-else
statement with the modulo check, and closing the scanner.
-
Save the file if you made any changes (Ctrl+S or Cmd+S).
-
Compile the program one last time to be sure:
javac HelloJava.java
-
Run the program and test it with both odd and even numbers (positive and negative) to confirm it works as expected.
java HelloJava
Example output for an odd number:
Enter an integer: 9
9 is an odd number.
Example output for an even number:
Enter an integer: -4
-4 is an even number.
You have now successfully implemented and verified a Java program that uses the modulo operator and an if-else
statement to determine if an integer is odd or even. This fundamental concept of conditional logic is crucial for building more complex programs.