Page 177 - CA_Blue( J )_Class9
P. 177

22          }
                  23      }

                       Input:                                       You will get the following output:


















                     8.3 TERMINATING A PROGRAM USING SYSTEM.EXIT()
                 System.exit() is a method in Java used to terminate the currently running program.
                 There are two types of terminations using System.exit():
                    1.  To exit normally, we use System.exit(0).
                    2.  To have an abnormal exit, System.exit(1) or System.exit(-1) or any other non-zero value is used.


                  Program 12     Input a number and print the square of the number. If the number is 0 then it will print an
                                 error message.
                   1      import java.util.*;

                   2      class square
                   3      {

                   4          public static void main()
                   5          {

                   6              Scanner sc = new Scanner(System.in);
                   7              int n,sq;

                   8          System.out.print("Enter the number: ");
                   9              n = sc.nextInt();
                  10              if (n == 0) {

                  11                System.out.println("Number should not be 0");

                  12                System.exit(0);
                  13              }
                  14              sq = n*n;

                  15              System.out.println("Square of  " + n + " = " + sq);
                  16          }

                  17      }



                                                                                     Conditional Constructs in Java  175
   172   173   174   175   176   177   178   179   180   181   182