* Answer 1: Using the modulus operator.
(1). Create project: CheckEvenOddModulus
(2). Create package: com.webmobileaz
(3). com.webmobileaz => File: Numbers.java
package com.webmobileaz; import java.util.Scanner; public class Numbers { public boolean isEven(int number) { return (number % 2 == 0); } } class Main { public static void main(String []args) { Scanner scan = new Scanner(System.in); System.out.print("Input a number: "); int number = scan.nextInt(); Numbers num = new Numbers(); if(num.isEven(number)) { System.out.println(number + " is Even"); } else { System.out.println(number + " is Odd"); } } }
Download Project: CheckEvenOddModulus
* Answer 2: You can use the modulus operator, but that can be slow. If it's an integer, you can use Bitwise AND operator
(1). Create project: CheckEvenOddBitwise
(2). Create package: com.webmobileaz
(3). com.webmobileaz => File: Numbers.java
package com.webmobileaz; import java.util.Scanner; public class Numbers { public boolean isEven(int number) { return ((number & 1) == 0); } } class Main { public static void main(String []args) { Scanner scan = new Scanner(System.in); System.out.print("Input a number: "); int number = scan.nextInt(); Numbers num = new Numbers(); if(num.isEven(number)) { System.out.println(number + " is Even"); } else { System.out.println(number + " is Odd"); } } }
Download Project: CheckEvenOddBitwise
0 comments:
Post a Comment