Find all even numbers using Java while also validating user input

By | July 17, 2019

Sometimes new programmers get stuck even in simplest task. Using Java, it’s easy to find whether or not a number is an even number. However, how about validating user input before we even begin our simplest task. This tutorial is for Java programmers who have started learning the language.

What is an even number?

If a number is fully divisible by 2 then it is an even number. To check whether or not a given number is an even number then we just need to look up to its modulus. In Java, to find modulus (remainder) of a division we use modulo operator (which is “%”).

You can read more in detail in the Wikipedia’s article.

How to use modulo operator?

To divide any two numbers we use “/” operator in Java. However, to find modulus (remainder) of that division we’ll have to use modulo operator “%”. For example:

int division = 8 / 2;        // Gives us 4 as result
int modulus = 8 % 2;         // Gives us 0 as result

Finding all even numbers between 0 and 100

Using above knowledge, now we know that if a number is completely divisible by 2 then the modulus (remainder) will be 0 for an even number. However, if modulus (remainder) is 1 then that would be an odd number. With this simple logic, we can write a For-Loop to find odd numbers between 0 and let’s say 100.

for (int i = 0; i <= 100; i++)
{
    if ((i % 2) == 0)
    {
        System.out.println(i + " is an even number");
    }
}

Find all even numbers up to user’s input

Instead of fixed number for our For-Loop in above code, we can ask user to give us a number to calculate even numbers up to that number:

import java.util.Scanner;

Scanner in = new Scanner(System.in);
int number = in.nextInt();
for (int i = 0; i <= number; i++)
{
    if ((i % 2) == 0)
    {
        System.out.print(i + " is an even number");
    }
}

Validation of user input

If you run code in above section, you’ll find that it works. However, there is a caveat. We have to check the user’s input. What if user mistakenly enter an invalid number, or a string, or enters nothing at all? Then our program will crash with error exception on function in.nextInt(). For that we have to use Try-Except block. We can also compact our output by replacing newline with tab when writing each number on screen. Then our source code would be as following:

import java.util.Scanner;

int number = 0;
System.out.print("Enter number: ");
String userInput = in.nextLine();

try
{
    number = Integer.parseInt(userInput);
}
catch (NumberFormatException ex)
{
   System.out.println("Input is not a number.");
   return;
}

for (int i = 0; i <= number; i++)
{
    if ((i % 2) == 0)
    {
        System.out.print(i + " is an even number");
    }
}

Complete code with more validations on user input

We can write few more validations on user input to make sure it is a correct number for our calculation. Moreover, we can compact output by using a tab character to separate numbers instead of newline. Our complete code would be like following:

import java.util.Scanner;

public class findAllEvenNumbers
{
    public static void main(String[] args)
    {
        int number = 0;
        Scanner in = new Scanner(System.in);

        // Display program's heading
        System.out.println("*** Find All Even Number ***");
        System.out.println("");

        // Get input from user
        System.out.println("To find all even numbers up to the given number.");
        System.out.print("Enter number: ");
        String userInput = in.nextLine().trim();

        // Validate user input
        if (userInput.isEmpty())
        {
            System.out.println("No input was given.");
            return;
        }

        // Validate user input by
        // trying to convert it to a number
        try
        {
            number = Integer.parseInt(userInput);
        }
        catch (NumberFormatException ex)
        {
           System.out.println("Input is not a number.");
           return;
        }
        catch (Exception ex)
        {
            System.out.println("Error Exception: " + ex.toString());
            return;
        }

        // Further validate input number.
        if (number < 0)
        {
            System.out.println("Please enter a positive number.");
            return;
        }

        // Find and display all even numbers.
        for (int i = 0; i <= number; i++)
        {
            if ((i % 2) == 0)
            {
                System.out.print(i + "\t");
            }
        }

        System.out.println("");
    }
}

You can also find above code in Github’s Gist here.

You may also be interested in following articles:

Leave a Reply

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