Hi,
I am learning Java. I want to do a program that can check a number if its odd or even. I have done it with C but now need your help with Java coding.
Thanks for the help in advance.
teenQ
Hi,
I am learning Java. I want to do a program that can check a number if its odd or even. I have done it with C but now need your help with Java coding.
Thanks for the help in advance.
teenQ
Logic:
I hope this helps you.Code:if (x % 2 == 0) { // even } if (x % 2 != 0) { // odd } ... or binary AND operator... if (( x & 1 ) == 0) { // even } if (( x & 1 ) != 0) { // odd }
Check Even-Odd:
This is your Java code.Code:import java.io.*; public class IfElse{ public static void main(String[] args) throws IOException{ try{ int n; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); n = Integer.parseInt(in.readLine()); if (n % 2 == 0) { System.out.println("Given number is Even."); } else { System.out.println("Given number is Odd."); } } catch(NumberFormatException e){ System.out.println(e.getMessage() + " is not a numeric value."); System.exit(0); } } }
Hey Thanks for such a prompt reply.
I am running the code right now.
Thanks.
I am in AP Java (high school). I'll show you how I'd check for even or odd!
I do not know how to make that box-within-a-reply, so I'll just enter the program application here:
Code:import java.util.Scanner; public class EvenOrOdd { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num = 0; System.out.println("Enter a number: "); num = input.nextInt(); if (num % 2 == 0) { System.out.println("The number you entered is even"); } else if (num % 2 != 0) { System.out.println("The number you entered is odd"); } } }
Bookmarks