A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
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.
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.
No 'How to Implement the Solution' section available. Please consider contributing.
No 'How to Run the Solution' section available. Please consider contributing.