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

Racing Thoughts

 There are times where I cannot help the thoughts that come into my mind. They're racing and I feel like I don't have any control ov...