Page 51 - CTS - CSA TP - Volume 2
P. 51

COMPUTER SOFTWARE APPLICATION - CITS




           EXERCISE 85 : Use the if and if … else statements


            Objectives

           At the end of this exercise you shall be able to
           •  know the different  syntax and use of if Statements (simple if , if…else, elseif ladder, nested if statements)
           •  develop java programs using if statement.

           Requirements

           Tools/Materials
           •   PC/Laptop with Window OS
           •   JDK Software
           •  Text editor (Visual studio / Sublime / Note pad)


           Procedure

           TASK 1: Checking if a number is even or odd

           import java.util.Scanner;
           public class EvenOddChecker {
           public static void main(String[] args) {
                   Scanner scanner = new Scanner(System.in);
           System.out.print(“Enter a number: “);
           int number = scanner.nextInt();

           if (number % 2 == 0) {
           System.out.println(number + “ is an even number.”);
                   } else {
           System.out.println(number + “ is an odd number.”);

                   }
           scanner.close();
               }
              }
           Explanation:

           This Java program, named EvenOddChecker, is designed to determine whether a given input number is even or
           odd. Here’s how it works:
           1  The program starts by importing the Scanner class from the java.util package. The Scanner class allows user
              input from the console.
           2  The EvenOddChecker class contains the main method, which is the entry point of the program.
           3  Inside the main method:
           •  It creates a new Scanner object named scanner to read input from the console.

           •  It prompts the user to enter a number by displaying the message “Enter a number: “.








                                                           36
   46   47   48   49   50   51   52   53   54   55   56