Sunday, February 4, 2024

Determine if a number is Odd or Even

Sometimes you want to be able to check if a number is odd or even. Here's a simple method that will do just that.

public class OddOrEven {

  public static void main(String[] args) {
    int i = Integer.valueOf(args[0]);
    System.out.println(oddOrEven(i));
  }

  public static String oddOrEven(int number) {
    if (number %2 == 0) {
      return "Even";
    } else {
      return "Odd";
    }
  }
}

Naturally you'll want to do some value checking for the number input at the command line. It could easily throw an InvalidNumberFormat exception. I think that's the exception that would be thrown.

No comments:

Post a Comment

Ever feel like no one is listening?

 Ever have that feeling that no one is listening to you? Yeah, that feeling. It can be a strong feeling to have, a hurtful feeling also. The...