Check Even-Odd:-Example

Ads
 

Check Even-Odd:-Example

Now, you have to learn about the syntax of If-Else construct.

Now, you have to learn about the syntax of If-Else construct.

Check Even-Odd:-Example

     

Now, you have to learn about the syntax of If - Else construct. How the If - Else construct used to flow the program control as for as needed. If - Else construct has illustrated by a given example.

Given example reads a integer value and check weather number is Odd or Even. In this example you will learn how to determine the Even or Odd for the given number entered through the keyboard. If the given condition is true then print the message Given number is Even otherwise the control of the program will jumps in the else block and print the message Given number is Odd. In this example a special exception has been also used, that is NumberFormatException which holds the error during the checking the entered data format. Entered data must be a number not a character or string. If you enter anything except numeric value then normal flow of the program is sent to the catch block and print the specified message. Full running code is provided with the example.

Here is the code of the program:-

import java.io.*;

public class IfElse{
  public static void main(String[] args) throws IOException{
  try{
 
 int n;
 
 BufferedReader in = 
  new 
BufferedReader(new InputStreamReader(System.in));
  n = Integer.parseInt(in.readLine());
 
 if (n % == 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);
  }
  }
}

Download Even-Odd Example

Ads

Ads