Why good programmers use methods in their programs

 

  • Good programmers will write many methods because:

    • Methods can be used to reduce redundant code

    • Methods enable a programmer to re-use their code.

    • Methods can also be used to modularize a problem

      I.e.:

      • Method can help keep the computer program simple and improve the quality of the program.

  • Let's see some examples on how to do it.

The greatest common divisor

Previously, we have studied how to find the GCD of the numbers x and y:

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        int x = input.nextInt();
        int y = input.nextInt();

        /* ---------------------------------
	   Algorithm to find GCD(x,y)
	   --------------------------------- */
        int k, min;
        int GCD = 1;    // Best GCD so far

        min = (x < y) ? x : y;

        for ( k = 2; k <= min; k++ )
        {
           if ( (x%k == 0) && (y%k == 0) )
              GCD = k;       // We found a better GCD
        }
       
        System.out.println(GCD);
    } 

The gcd( ) method

 

  • Instead of running a Java program that reads in the numbers x and y and compute their GCD, it is better to make a method gcd(x,y) that compute the GCD of x and y:

      z = gcd( 24, 36 );
    
    or:
    
      z = gcd(x, y);
      

  • We can call the gcd(x, y) whenever we need to find the GCD of 2 numbers x and y !!!

The gcd( ) method

Let's write the gcd( ) method:

    public static  ???  gcd( ??? )   // What are the inputs and output ?
    {












    }

(1) what are the (input) parameters needed by gcd( ) use to do its work ?
(2) what is the type of value that is produced by gcd( ) as result ?

The gcd( ) method

The method header of gcd( ):   (1) gcd( ) needs 2 input numbers and (2) will produce an int result

    public static  int  gcd(int x, int y) // You can use any name for the parameters
    {












    }

Now write the body to compute the GCD of x and y
Note: we can copy from our previous program !

The gcd( ) method

The method body of gcd( ):

    public static  int  gcd(int x, int y)
    {
        int k, min;
        int GCD = 1;    // Best GCD so far

        min = (x < y) ? x : y;

        for ( k = 2; k <= min; k++ )
        {
           if ( (x%k == 0) && (y%k == 0) )
              GCD = k;       // We found a better GCD
        }
       
        System.out.println(GCD); // ???
    }

There is a small problem:   we do not want to print the GCD
Instead, we want to return the GCD ! ---- Can you make this change ???

The gcd( ) method

The completed gcd( ) method:

    public static  int  gcd(int x, int y)
    {
        int k, min;
        int GCD = 1;    // Best GCD so far

        min = (x < y) ? x : y;

        for ( k = 2; k <= min; k++ )
        {
           if ( (x%k == 0) && (y%k == 0) )
              GCD = k;       // We found a better GCD
        }
       
        return(GCD); // Return the GCD
    }

We can now invoke the gcd( ) method as: gcd(24, 36)
And we can do it any numbers of times and with any 2 integers !!!

The gcd( ) method    example usage

 

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        int z = gcd(24,36);
        System.out.println("GCD of 24 and 36 = "
                            + z);
        
        int x = input.nextInt();
        int y = input.nextInt();
        
        z = gcd(x,y);
       
        System.out.println("GCD of " + x + 
                    " and " + y + " = " + z);
    }
    public static  int  gcd(int x, int y)
    {
        int k, min;
        int GCD = 1;    // Best GCD so far

        min = (x < y) ? x : y;

        for ( k = 2; k <= min; k++ )
        {
           if ( (x%k == 0) && (y%k == 0) )
              GCD = k; // a better GCD
        }
       
        return(GCD); // Return the GCD
    }

We can store the gcd( ) method inside the Tools class
In that case, we must call it with: Tools.gcd(x, y)

DEMO: demo/06-methods/04-method-usage/Demo1.java + Tools.java + UseGCD.java

Testing if a number is prime

Previously, we have studied how to determine if number num is prime:

   public static void main(String[] args) 
   {
      Scanner input = new Scanner(System.in);
      
      int num = input.nextInt();

      /* -------------------------------------------
         Algorithm to determine if "num" is prime
         ------------------------------------------- */
      boolean isPrime = true;
      int i;

      for ( i = 2; i < num; i++ )
      {
          if ( num%i == 0 )
          {
             isPrime = false;
             break;
          }
          
      }
      System.out.println(isPrime);
   }

The isNumberPrime( ) method

 

  • Instead of running a Java program that reads in the number num, it is better to make a method isNumberPrime(num) that determines if num is a prime number (or not):

      boolean result = isNumberPrime( 951 );
    
    or:
    
      boolean result = isNumberPrime( x );
      

  • We can call the isNumberPrime(x) whenever we need to determine if some integer x is a prime number !!!

The isNumberPrime( ) method

Let's write the isNumberPrime( ) method:

    public static  ???  isNumberPrime( ??? )   // What are the inputs and output ?
    {













    }

(1) what are the (input) parameters needed by isNumberPrime( ) use to do its work ?
(2) what is the type of value that is produced by isNumberPrime( ) as result ?

The isNumberPrime( ) method

The method header of isNumberPrime( ): (1) method needs 1 input number and (2) outputs true or false

    public static boolean isNumberPrime(int num) 
    {













    }

Now write the body to determine if num is a prime number
Note: we can copy from our previous program !

The isNumberPrime( ) method

The method body of isNumberPrime( ):

    public static boolean isNumberPrime(int num) // You can use any name !
    {
      boolean isPrime = true;
      int i;

      for ( i = 2; i < num; i++ )
      {
          if ( num%i == 0 )
          {
             isPrime = false;
             break;
          }     
      }

      System.out.println(isPrime); // ???
    }

There is a small problem:   we do not want to print the variable isPrime
Instead, we want to return the value of isPrime variable ! ---- Can you make this change ???

The isNumberPrime( ) method

The completed isNumberPrime( ) method:

    public static boolean isNumberPrime(int num) // You can use any name !
    {
      boolean isPrime = true;
      int i;

      for ( i = 2; i < num; i++ )
      {
          if ( num%i == 0 )
          {
             isPrime = false;
             break;
          }     
      }

      return(isPrime); // Return the value
    }

We can now invoke the isNumberPrime( ) method as: isNumberPrime(x)
And we can do it any numbers of times and with any integer !!!

The isNumberPrime( ) method    example usage

 

    // Print all prime numbers <= 100

    public static void main(String[] args)
    {
        int i;
        
        for ( i = 2; i <= 100; i++ )
            if ( isNumberPrime(i) )
                System.out.print(i + " ");

        System.out.println();
    }




    public static boolean isNumberPrime(int num)
    {
      boolean isPrime = true;
      int i;

      for ( i = 2; i < num; i++ )
      {
          if ( num%i == 0 )
          {
             isPrime = false;
             break;
          }     
      }

      return(isPrime); // Return the value
    }

We can store the isNumberPrime( ) method inside the Tools class
In that case, we must call it with: Tools.isNumberPrime(x)

DEMO: demo/06-methods/04-method-usage/Demo2.java + Tools.java + UseIsPrime.java

Palindrome homework exercise    Write a isWordPalindrone( ) method

Previously we have written a program to check for palindromes:

   public static void main(String[] args) 
   {
      Scanner input = new Scanner(System.in);
      
      String x = input.next();

      /* ------------------------------------------
         Algorithm to check if x is a palindrome
	 ------------------------------------------ */
      boolean isPalindrome = true;
      int i, last;
      
      last = x.length() - 1;

      for ( i = 0; i < x.length()/2; i++ )
      {
          if ( x.charAt( i ) != x.charAt( last-i ) )
          {
              isPalindrome = false;
              break; // We can exit the loop now
          }
      }

      System.out.println(isPalindrome);
   } 

Use this algorithm to write an isWordPalindrome(s) method that checks if s is a palindrome