Even Odd in Java

Published on 28 April 2022 (Updated: 25 September 2022)

Even Odd in Java

Welcome to the Even Odd in Java page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

public class EvenOdd
{
    public static void verifyNumber(String n) throws NumberFormatException
    {
        if (n.startsWith("-"))
            n = n.substring(1);
        char[] nArray = n.toCharArray();
        for (char c : nArray)
        {
            if (!Character.isDigit(c))
                throw new NumberFormatException();
        }
    }

    public static void ErrorAndExit()
    {
        System.out.println("Usage: please input a number");
        System.exit(1);
    }

    public static void main(String[] args)
    {
        try
        {
            String nstr = args[0].trim();
            verifyNumber(nstr);
            String lastDigit = nstr.substring(nstr.length() - 1);
            int n = Integer.parseInt(lastDigit);
            String result = n % 2 == 0 ? "Even" : "Odd";
            System.out.println(result);
        }
        catch (NumberFormatException | ArrayIndexOutOfBoundsException | StringIndexOutOfBoundsException e)
        {
            ErrorAndExit();
        }
    }
}

Even Odd in Java was written by:

If you see anything you'd like to change or update, please consider contributing.

Note: The solution shown above is the current solution in the Sample Programs repository as of Mar 28 2019 15:21:26. The solution was first committed on Dec 30 2018 18:17:14. As a result, documentation below may be outdated.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.