Yesterday, our professor assigned an exercise about the basics of programming logic: creating a program to check if a given number is odd or even. While it may seem simple at first glance, this exercise reinforces key skills in user input, conditional statements, and error handling.
In this post, we’ll explore the Java solution for this exercise, breaking down each part of the code to understand how we can efficiently determine if a number is odd or even, while also handling potential input errors. This exercise not only helps with basic programming fundamentals but also provides a good refresher on handling exceptions and user inputs gracefully.
Program Overview
This Java program:
- Takes an integer input from the user.
- Checks if the number is even or odd.
- Prints the result to the console.
- Handles invalid inputs gracefully by catching exceptions.
Code Explanation
Let’s walk through the code step-by-step to understand how it works.
import java.io.*; public class EvenOddNumber { public static void main(String[] args) throws IOException { try { int n; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Number : "); n = Integer.parseInt(in.readLine()); if (n % 2 == 0) { System.out.println("Given number is Even."); } else { System.out.println("Given number is Odd."); } } catch (NumberFormatException e) { System.out.println(e.getMessage() + " is not a numeric value."); System.exit(0); } } }
Step-by-Step Breakdown
1. Importing Required Libraries
import java.io.*;
The program imports the java.io
package to enable input handling. Specifically, we use BufferedReader
for reading user input from the console.
2. Main Method Declaration
public static void main(String[] args) throws IOException {
- The
main
method is the entry point for the program. - It declares
throws IOException
to handle potential input/output exceptions. However, sinceIOException
is also managed within a try-catch block, this statement could technically be omitted here.
3. Initializing Variables and Setting Up Input
int n; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Number : ");
int n;
: Declares an integer variablen
to store the user input.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
: Initializes aBufferedReader
object to read input from the console.
4. Taking Input and Parsing it as an Integer
n = Integer.parseInt(in.readLine());
in.readLine()
reads a line of input from the console as aString
.Integer.parseInt()
converts thisString
to an integer. If the user enters a non-numeric value, this will throw aNumberFormatException
, which we handle in thecatch
block.
5. Checking if the Number is Even or Odd
if (n % 2 == 0) { System.out.println("Given number is Even."); } else { System.out.println("Given number is Odd."); }
n % 2
calculates the remainder whenn
is divided by 2.- If
n % 2 == 0
, the number is even (as it’s perfectly divisible by 2). - If
n % 2 != 0
, the number is odd.
- If
- The program prints either "Given number is Even" or "Given number is Odd" based on the condition.
6. Handling Exceptions
catch (NumberFormatException e) { System.out.println(e.getMessage() + " is not a numeric value."); System.exit(0); }
- The
catch
block catches anyNumberFormatException
, which occurs if the user inputs a non-numeric value. - The program outputs a message indicating that the input is not a number, along with the specific invalid input.
System.exit(0);
terminates the program after handling the exception.
Sample Output
Case 1: Valid Even Number
Enter Number: 4 Given number is Even.
Enter Number: 7 Given number is Odd.
Enter Number: abc abc is not a numeric value.
Explanation of Key Concepts
Input and Output
- BufferedReader:
BufferedReader
withInputStreamReader
is used for reading input from the console. This is a standard way of handling I/O in Java, especially before the introduction of the Scanner class.
Exception Handling
- NumberFormatException: This exception is used to catch cases where the input cannot be parsed as an integer, such as when the user inputs letters instead of numbers. This is essential for making programs more user-friendly by handling errors gracefully.
Modulus Operator
- % (Modulus): This operator returns the remainder of the division of one number by another. In this case,
n % 2
is used to check ifn
is divisible by 2, which determines if the number is even or odd.
Conclusion
This program is a straightforward example that demonstrates:
- Basic input handling in Java.
- Using conditional statements to check for even or odd numbers.
- Exception handling to manage unexpected input errors.
Programs like this one help solidify foundational concepts and encourage proper error handling, providing a base for more complex programs in Java.