Home > Tutorial > Java Scanner Input Odd Even Example

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 Print Alphabet 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 Print Alphabet 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!


Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot