English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to check if the number entered by the user is even or odd. This will be done using the if...else statement and the ternary operator in Java.
import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter an integer: "); int num = reader.nextInt(); if(num % 2 == 0) System.out.println(num + "is even") else System.out.println(num + "is odd") } }
When running the program, the output is:
Enter an integer: 12 12 for even numbers
In the above program, a Scanner object reader is created to read numbers from the user's keyboard. The input number is then stored in the variable num.
Now, to check if num is even or odd, we use the % operator to calculate the remainder and check if it is divisible by2divisible by.
To do this, we use the if...else statement in Java. If num is divisible by2If it is divisible, we print out that num is even. Otherwise, we print out that num is odd.
We can also use the ternary operator in Java to check if num is even or odd.
import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter an integer: "); int num = reader.nextInt(); String evenOdd = (num % 2 == 0) ? "Even" : "Odd"; System.out.println(num + "Odd" + evenOdd); } }
When running the program, the output is:
Enter an integer: 13 13 Odd
In the above program, we replaced the if...else statement with the ternary operator (? :).
Here, if num is2If it is divisible, return "Even". Otherwise, return "Odd". The returned value is stored in the string variable evenOdd.
Then, use string concatenation to print the result on the screen.