偶数是可以被2整除的数字。因此,对给定数字执行%2运算,如果结果为0,则给定数字为偶数,否则给定数字为奇数。
import java.util.Scanner; public class EvenOrOdd { public static void main(String args[]){ //从用户读取号码 Scanner sc = new Scanner(System.in); System.out.println("Enter a number ::" ); int num = sc.nextInt(); //求偶数或奇数 if (num % 2 == 0){ System.out.println("Entered number is an even number"); } else { System.out.println("Entered number is an odd number"); } } }
Enter a number :: 9 Entered number is an odd number
Enter a number :: 8 Entered number is an even number