Page 458 - CA_Blue( J )_Class10
P. 458

(d)  Program depicting the concept of non-static method.


                Program 4    Write a non-static method to accept a number and check the number is a prime number or not.



                 1      import java.util.*;       // importing package util

                 2      class prime_nonstaticmethod
                 3      {    int n;           // Instance Variable

                 4          void primemethod()
                 5          {

                 6              int c=0, i;
                 7              for(i=1;i<=n;i++)       // Loop for checking prime

                 8              {
                 9                  if(n%i==0)       // checking whether "n" is divisible by "i"

                10                  {
                11                      c++;

                12                  }
                13              }

                14              if(c==2)         // checking whether counter is 2 for find prime
                15                  System.out.println(n + " is prime number");

                16              else
                17                  System.out.println(n + " is not prime number");

                18          }
                19          void main()

                20          {   Scanner sc= new Scanner(System.in);
                21              System.out.println("Enter a number ");

                22              n=sc.nextInt();            // number taken for checking prime
                23              primemethod();            // Invoking primemethod()
                24          }

                25      }

              Output
              Enter a number : 17

              17 is prime number
              Enter a number : 18

              18 is not prime number





                456456  Touchpad Computer Applications-X
   453   454   455   456   457   458   459   460   461   462   463