Java Scanner Input Odd Even Example

The sample Java program below will read user input from the command line using the Scanner class and determine if number is odd or even. Implementing this in a while loop allows for continual user input of checking whether or not a number is odd or even.

Determining if a number is odd or even is simple by using the Java division operator. In our example, we simple divide the number by two. The program will quit by entering 0 on the command line.


Java Scanner Input Odd Even Source Code

package com.jcd.java.tutorials;

import java.util.Scanner;

public class JavaScannerOddEven 
{

	public static void main(String[] args) 
	{

		int jcdNum;
		 
		//Create Scanner object ot read command line input
	    Scanner jcdInput = new Scanner(System.in);
	    
	    System.out.println("Input a Number"); 
	 
	    //Keep asking for a number within the while loop (0 to exit)
	    while ((jcdNum = jcdInput.nextInt()) != 0) 
	    {
	      
	    	System.out.println("Number Entered: " + jcdNum);
	      
	    	if ( jcdNum % 2 == 0 )
	    	{
	    		System.out.println("JavaCodeDepot Determined that was an Even Number");
	    	}
	    	else
	    	{
	    		System.out.println("JavaCodeDepot Determined that was an Odd Number");
	    	}
	    }
	    
	    //Cleanup and close the Scanner input
	    jcdInput.close();
	 
	    
	    System.out.println("Finished!");

	}

}


Java Scanner Input Odd Even Output

Input a Number
2
Number Entered: 2
JavaCodeDepot Determined that was an Even Number
4
Number Entered: 4
JavaCodeDepot Determined that was an Even Number
11
Number Entered: 11
JavaCodeDepot Determined that was an Odd Number
21
Number Entered: 21
JavaCodeDepot Determined that was an Odd Number
345678
Number Entered: 345678
JavaCodeDepot Determined that was an Even Number
12321
Number Entered: 12321
JavaCodeDepot Determined that was an Odd Number
0
Finished!


Add a Comment

Your email address will not be published. Required fields are marked *