INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM

ICS102, SECTIONS 52, 54 & 55  (001 Semester)

INTRODUCTION TO COMPUTING

LAB  #07 Methods & Parameter passing

 

Instructor: Bashir M. Ghandi

 


Objectives:

To gain experience with:

 

 

1.  Introduction to Abstraction (Simplicity is good; complexity is bad).

The most effective weapon that computer scientists have in their fight against complexity is abstraction. Abstraction means concentrating on the essentials and ignoring the details.

Sometimes abstraction is described as "remembering the 'what' and ignoring the 'how'".

Large complex programs can only be made understandable by decomposing them into modules. When viewed from the outside, each module should be simple, with the complexity hidden inside.

When we develop an algorithm following the top-down approach, we are practicing procedural abstraction. At a high level, we break the problem up into several tasks. We give each task a name and state its requirements, but we do not worry about how the task is to be accomplished until we expand it at a lower level of our design.

When we code a task in a programming language, we will typically make each task a procedure (or function). Any other program component that calls the procedure needs to know its interface (name, parameters, assumptions, etc.) but does not need to know the procedure's internal implementation details. The internal implementation can be changed without affecting the caller.  In Java such procedures or functions are called methods.  methods have the following format:

<access modifiers> <type> Name (<parameters>) <modifiers>
{
   <statements that are the method body>
   <one or more return statements (for a non-void method)>
   }

 

Example 1:  The following program simulates a banking system, which initializes a customer account with SR5000 and then allows him to withdraw, deposit or enquire about his balance.  The system continue to run until the user chooses “E” to exit

import TextIO;

import java.io.IOException;

/* display a menu and allow the user to perform a banking transaction*/

public class BankingSystem {

      static TextIO stdin = new TextIO(System.in);

      private static double balance = 5000;

     

    public static void main (String args [ ]) throws IOException {

      char choice;

      do {

            showMenu();

            choice = getChoice();

            switch (choice) {

                  case 'W' :  withdraw();

                              break;

                  case 'D' :  deposit();

                              break;

                  case 'B' :  showBalance();

                              break;

            }

      } while (choice != 'E');

    }

   

    public static void showMenu() {

            System.out.println("\n***************************");

            System.out.println("*  XYZ   Banking  System  *");

            System.out.println("***************************\n");

            System.out.println("W. Withdraw");

            System.out.println("D. Deposit");

            System.out.println("B. Balance");

            System.out.println("E. Exit");

    }

     

      public static void withdraw() throws IOException{

         double amount;

         System.out.print("Please Enter Amount to Withdraw: ");

         amount=stdin.readDouble();

         if (amount <= balance)

              balance -=amount;

         else

            System.out.println("Sorry,you do not have that much!");       

         showBalance();

   }

  

   public static void deposit() throws IOException {

        double amount;

        System.out.print("Please Enter amount to Deposit: ");

        amount=stdin.readDouble();

        balance+=amount;

        showBalance();

   }

  

   public static void showBalance() {

        System.out.println("Your Balance is: "+balance);

   }

  

   public static char getChoice() throws IOException{

      char ch;

      System.out.print("Please Enter Your Choice (W, D, B, E) : ");

      ch = stdin.readChar();

      ch = Character.toUpperCase(ch);

      return (ch);

   }

}

Notes:

·         Although the program looks a little long, its purpose can easily be understood by reading the main method, which is indeed very small and straight to the point.  This is one of the main the advantages of abstraction.

·         Variables declared inside a method are called local variables.  e.g. amount in the withdraw method.  These types of variables exist only during each execution of the method. They do not exist in between executions of the same method, so their values do not "carry over" to the next call of the same method.  Their scope (visibility) is from the point they are declared to the end of the method body – they are not visible in another method.

·         Variables declares inside the class are called global variables and they can be accessed by each method in the class.  e.g. is balance.

·         If a method returns a result then it is called as part of another statement such as assignment statement or print statement.  Example is             choice = getChoice();

·         For void methods, they are called on their own, not as part of any other statement. e.g. deposit() and withdraw()

 

2.  Parameter passing

In addition to returning a value as output, methods can also receive input from their caller through parameters.

 

Example 2: The following example modifies the temperature tabulation program of last lab by abstracting the process of tabulation into a method.  Notice that in this case, we need to pass the starting and stopping temperature as well as the increment as parameters to the method.

/* reads initial and final temperature in Celsius and the incremental value

   prints a table of both Celsius and equivalent Fahrenheit temperatures

*/

import TextIO;

import java.text.DecimalFormat;

 

public class TemperatureTable4 {

 

      static TextIO stdin = new TextIO(System.in);

 

      public static void main(String[] args) throws java.io.IOException  {

 

            double start, stop, increment;

           

            do {

                  System.out.print("Enter starting temperature in Celsius: ");

                  start=stdin.readDouble();

                  System.out.print("Enter stopping temperature in Celsius: ");

                  stop=stdin.readDouble();

                  System.out.print("Enter increment value: ");

                  increment=stdin.readDouble();

                  System.out.println();

           

                  if (stop > start) {

                    System.out.println("CELSIUS"+"\t\t"+"FAHRENHEIT");

                    showTable(start, stop, increment);

                  }

                  else

                        System.out.println("Starting Temperature must be smaller

                           than stopping temperature");

            }while (stop <= start); 

      }

     

      public static void showTable(double start, double stop, double stepBy) {

            DecimalFormat df3 = new DecimalFormat("0.000");

            double fahrenheit;

           

      for (double celsius=start; celsius<=stop; celsius+=stepBy) {

            fahrenheit = 9.0/5.0*celsius+32;

             System.out.println(df3.format(celsius)+"\t\t"+df3.format(fahrenheit));

            }

      }

}

 


Notes:

·         The parameters in the definition of a method are called formal parameters.  e.g. the parameters in the definition of showTable indicated in blue above.

·         Formal parameters are not assigned values until the method is called.  Example of method call is shown in magenta in the main method.  The values used to call the method are called actual parameters. 

·         When a method is called, the formal parameters are initialized with the values of the actual parameters before control is passed to the called method.

·         Formal parameters and Actual parameters are independent, thus they may have the same or different names as shown in the above example.

·         Formal and actual parameters must match in number and order.  Also they must match in type except where there will be no loss of information.  e.g. if a formal parameter is double, then its corresponding actual parameter may be int.

·         Actual parameters do not have to be variables, but could be any expression that will result in a value that is compatible with the corresponding actual parameter.  e.g.  The we can call the showTable method above as:

showTable(start-5, stop+5, increment/2);

 

Example 3:  The following example computes the number of possible ways of choosing k items from a total of n items.  Mathematically, this is given by the formula:

.

mport TextIO;

/* computes the number possibilities (combination) in choosing a group

   from a given population

*/

class NChooseK {

 

  static TextIO stdin = new TextIO(System.in);

 

  public static void main(String args[]) throws java.io.IOException{

 

    int population, group;

    long count;

 

    System.out.print("Enter the population size: ");

    population = stdin.readInt();

    System.out.print("Enter the group size: ");

    group = stdin.readInt();

 

    count = choose(population,group);

    

    System.out.println("There are " + count + " ways of selecting " + group +

                           " objects from " + population + " objects.");

  }

 

  public static long choose(int n, int k) {

 

    return (factorial(n) / (factorial(n-k) * factorial(k)));

 

  }

 

  public static long factorial(int n) {

 

    long product = 1;

 

    for (int i = 2 ; i <= n ; i++) {

      product *= i;

    }

 

    return product;

  }

}

 

 

3.  Assignments

1.    Write a program that reads three integer numbers and prints the maximum, the minimum and the average.  In addition to the main method which should only reads the input and prints the result, your program should have three other methods whose format is given below: 

                                                                  public static int maximum (int n1, int n2, int n3)

                  public static int minimum (int n1, int n2, int n3)

                  public static double average (int n1, int n2, int n3)

 

2.    Write a program that simulates a simple arithmetic calculator, which displays a menu and allows a user to perform addition, subtraction, multiplication and division, as shown by the following sample run.  Your program should contain the methods for the different operations:    

                                  public static void showMenu()

                           public static int getChoice() throws IOException

                           public static double add(double op1, double op2)

                             (similarly for subtract, multiply and divide).

 

3.        Write a program that reads the sides of a triangle and determine the type of the triangle.  The possibilities are:

               

Right-angle

square of one side is same as sum of the squares of the other two sides

Equilateral

all sides are equal

Isosceles

two of the sides are equal

Scalene

no two sides are equal

 

You should have a boolean method to test for each of the above types. Your program should repeat until 0 0 0 is entered.