Even Odd in Java

Published on 30 December 2018 (Updated: 10 October 2022)

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.

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.