SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
Week 5
Software
Construction:
Methods
Copyright Warning
               COMMONWEALTH OF AUSTRALIA
                   Copyright Regulations 1969
                           WARNING
 This material has been copied and communicated to you by or
    on behalf of Bond University pursuant to Part VB of the
                  Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright
  under the Act. Any further copying or communication of this
   material by you may be the subject of copyright protection
                         under the Act.


Do not remove this notice.




Š 2004 Pearson Addison-Wesley. All rights reserved         5-2
Software Construction
• As programs become larger, they become more
  complicated
        more variables, more loops, more nested structures
• We need ways to isolate this complexity
• All computer languages provide mechanisms to do
  this, e.g.
        methods, classes, packages, libraries, whole programs
• This week, we are going to look at methods




Š 2004 Pearson Addison-Wesley. All rights reserved               5-3
Methods
• A method is a “mini-program”, with its own
  variables and lines of code
• It usually get input by means of variables which
  are passed to it
• The method can return one value, which is the
  result of the “mini-program”
• From the caller's point of view, the method is a
  black box which performs some work, e.g
            answer= generator.nextInt(MAX);



Š 2004 Pearson Addison-Wesley. All rights reserved   5-4
Some You Have Seen Already
• You have already used methods. Some take input
  but provide no outputs, e.g
        System.out.print(“hello”);
        System.out.println(“hello”);
• Some methods take no input but return a value,
  e.g.
        guess= scan.nextInt();
        name= scan.nextLine();
• Some take no inputs, and return nothing, e.g
        public static void main();
• Taking input is optional, and so is returning a
  value.
• It's up to the designer of the method to decide
  what is required to make the method work
Š 2004 Pearson Addison-Wesley. All rights reserved   5-5
Why Methods?
• Methods help to isolate complexity: code to do a
  certain task is contained within a method
• Methods allow you to think in terms of
  “components”:
    get user input, print out a header, determine if a number
     is valid
    once you have written a method and tested that it is
     correct, you can use it as a black box component
• Methods enforce the DRY Principle: don't repeat
  yourself.
    If you write the same code twice, bad. Why?
    Convert it into a method, then call the method multiple
     times
• Methods can be tested. This helps to prove that
     your components work correctly
Š 2004 Pearson Addison-Wesley. All rights reserved             5-6
Your First Method
• Let's write a method to find the biggest of two
  numbers.
• What inputs does it require?
        two integers
• Does it need to return a value?
        Yes, the value of the biggest number
• OK, let's call the two integers a and b
• We can write some of the Java code now:
  if (a>b)
    // then a is bigger, return its value
  else
    // b is bigger, return it instead

Š 2004 Pearson Addison-Wesley. All rights reserved   5-7
The return keyword
• The return keyword is used to return a value out of
  a method. We can modify our code:

     if (a>b)
       return(a);
     else
       return(b);

• Note: the return ends the execution of the method.
  If we return(a), then the code from else
  onwards will not get executed
• All return()s in a method must return the same
  type of data. Here, we always return an int
Š 2004 Pearson Addison-Wesley. All rights reserved   5-8
Declaring the Method
• We must now declare the method. This tells the
  other Java code how to use the method and what it
  will return
    The method's name is maxOf
    It takes two integers as input
    It returns a single int value


     public static int maxOf(int a, int b)
     {
           if (a>b)
                 return(a);
           else
                 return(b);
     }
Š 2004 Pearson Addison-Wesley. All rights reserved   5-9
Trying It Out With Bluej
• Let's try the code out in Bluej
     Open a new program, note that it already comes with a
      method called main()
     Add the maxOf() code after the code for main()
     Compile the program
• Now right-click on the file. You will see




• 2004 Pearson Addison-Wesley.maxOf() method
Š
     Select the All rights reserved                           5-10
Trying It Out With Bluej
• Bluej will provide you with a window to enter the
  input values to the method




• Enter two values and click OK
• Bluej runs the method, and shows you the result
  returned by the method



Š 2004 Pearson Addison-Wesley. All rights reserved   5-11
Calling a Method
• Now it's time to call the method with real Java
  code. Modify the main() method to have this
  code:
    int num1, num2, result;
    num1= 76; num2= 3004;
    result= maxOf(num1, num2);
    System.out.println(“The result is” +
                                 num1);

            System.out.println( maxOf(2, 17-8) );

• Try to guess what will get printed out when the
  main() method is run
Š 2004 Pearson Addison-Wesley. All rights reserved   5-12
Terminology
• The list of variables that are the inputs to a method
  are known as its formal parameters
        int maxOf(int a, int b)
          a & b are formal parameters
• The values that are used when a method is called
  are its actual parameters, or its arguments
                      result= maxOf(2, 17-9);
                  2 and 17-9 are the arguments
• The values of the arguments are calculated, and
  copies of these values are assigned into the formal
  parameters when the method is called



Š 2004 Pearson Addison-Wesley. All rights reserved   5-13
Call by Value
• Copying the values of the arguments into a
  method is known as call by value
  result= maxOf(2, 17-9);

                                  maxOf(int a, int b)

                                                 return(...);

• Similarly, the value returned by the method is
  copied back out the the caller of the method
• The formal parameters, and any variables declared
  in the method are local variables
• They are not visible outside the method
Š 2004 Pearson Addison-Wesley. All rights reserved              5-14
Methods are Expressions
• Methods return a value. Therefore, they can be
  treated as expressions
• You do not have to assign the result of a method
  call, e.g in main():
            int num1, num2;
            System.out.print(“Enter a num: “);
            num1= scan.nextInt();
            System.out.print(“Enter a num: “);
            num2= scan.nextInt();
            System.out.println( 11 + maxOf(num1,num2) );
• If the user entered 50 and 61, the last line would
  calculate 11 + 61, and print out 72


Š 2004 Pearson Addison-Wesley. All rights reserved     5-15
Designing Methods 1
• Methods are the basic components of any large
  program
• With few exceptions, methods should
    get their inputs as formal parameters, and return a result
     if required,
    not print anything out to the user, and
    not get any input from the user
• The last 2 rules allow the caller of a method to
     decide if they want to print something out to the
     user
• However, it is legal to write a method to prompt a
     user, get input and validate that input
• Similarly, if user output is complicated, then it's
     OK to place the code in a method
Š 2004 Pearson Addison-Wesley. All rights reserved     5-16
Input Method Example
public static double getHeight()
{
  double userheight;
  Scanner scan = new Scanner (System.in);

     while (true)
     {
       System.out.print(“Enter your height: “);
       userheight= scan.nextDouble();
       // Only accept if between 1.2m and 2.4m
       if ((userheight>=1.2) && (userheight<=2.4))
         return(userheight);
       System.out.println(“Try again...”);
     }
}

Š 2004 Pearson Addison-Wesley. All rights reserved   5-17
What's void?
• We have to declare what type of value a method
  returns
• What if it never returns a value? We declare it to
  return void, e.g.
        public static void printGrade(int mark)
        {
             if (mark<50)
                 System.out.println(“FL”);
             else if (mark<65)
                 System.out.println(“PS”);
             else if (mark<75)
                 System.out.println(“CR”);
             else if (mark<85)
                 System.out.println(“DN”);
             else
                 System.out.println(“HD”);
        }
Š 2004 Pearson Addison-Wesley. All rights reserved     5-18
Methods Can Call Other Methods
• Methods contain ordinary Java code; this code
  can call other methods
• This has been shown in the examples on the
  previous slides, e.g
    getHeight() called System.out.print()
     and scan.nextDouble()




Š 2004 Pearson Addison-Wesley. All rights reserved   5-19
Method Control Flow
• When a method calls another method, execution of
  the program diverts into that method


                      main                             doIt      helpMe




             obj.doIt();                             helpMe();




Š 2004 Pearson Addison-Wesley. All rights reserved                        5-20
Designing Methods 2
• The declaration of an a method is known as its
  interface
• It describes how other methods use it
• When designing large programs, cut the task up
  into sub-tasks, where a sub-task is done by one
  method
• Design the interface to the method first:
    what inputs does it need to do the job?
    what result if any will it return?
• Once you know what each method will do, then
  you can write the code for the method
• This gives you a broad idea of the solution, before
  you have filled in the details
Š 2004 Pearson Addison-Wesley. All rights reserved   5-21
Design Time
• As a class, design declarations for these methods:
• A method to count the number of uppercase
  letters in a string
• A method that, given a letter and a count, returns a
  string with that many of the letters
• A method that indicates if a given number is a
  prime (true) or is not a prime (false)
• A method to convert a Celsius temperature to
  Fahrenheit
• A method that, given a string, indicates if the
  string has no uppercase letters in it
• A method that, given a letter and a count, draws a
  box using that letter. Each side has count letters
Š 2004 Pearson Addison-Wesley. All rights reserved   5-22
Design Time 2
• Now, write the full method to count the number of
  uppercase letters in a string
• Hint: Use the existing methods in the String class,
  especially length() and charAt()
• Hint: You need to check out each letter, so you will
  need a loop. What type?
• Hint: Do you know the length of the string?

• Can you think of some inputs and outputs that will
  show if the method is working correctly?
• Think of some very unusual strings to try out


Š 2004 Pearson Addison-Wesley. All rights reserved   5-23
Unit Testing
• All large programs have bugs: usual estimate is 1
  bug per 100 lines of code
• Most bugs are logic bugs: the programmer thinks
  it works, but the code does something different
• It's nearly impossible to tell if a program is 100%
  bug-free
• Implication: programs should be tested thorougly
  to give assurance there are no bugs
• Unit testing: test a method with a large set of
  inputs, to ensure that it produces the correct
  output
• The test set is designed to stress the method as
  much as possible
Š 2004 Pearson Addison-Wesley. All rights reserved   5-24
Unit Testing
•    You should design the method interface first
•    THEN, construct a suitable test set for it
•    ONLY THEN, write the actual method code
•    Once you think you have written the method, you
     can then test the method with the unit tests
•    “Coding isn't complete until all the unit tests pass”
•    ALWAYS generate the tests by hand. Don't use a
     program to generate the test set. Why not?
•    Bluej provides a framework to construct unit tests.
•    You will see it in the labs, and you will be
     assessed on its use

Š 2004 Pearson Addison-Wesley. All rights reserved     5-25

Weitere ähnliche Inhalte

Was ist angesagt?

C++ programming intro
C++ programming introC++ programming intro
C++ programming intromarklaloo
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2sumitbardhan
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notesSrikanth
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smellskim.mens
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of VariableMOHIT DADU
 
Object Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsObject Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsMuhammadTalha436
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1YOGESH SINGH
 
Csci360 08-subprograms
Csci360 08-subprogramsCsci360 08-subprograms
Csci360 08-subprogramsBoniface Mwangi
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101Adam Culp
 
Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoringYuriy Gerasimov
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...Make Mannan
 
10 implementing subprograms
10 implementing subprograms10 implementing subprograms
10 implementing subprogramsMunawar Ahmed
 

Was ist angesagt? (20)

C++ programming intro
C++ programming introC++ programming intro
C++ programming intro
 
Python recursion
Python recursionPython recursion
Python recursion
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
 
sCode optimization
sCode optimizationsCode optimization
sCode optimization
 
Optimization
OptimizationOptimization
Optimization
 
Python algorithm
Python algorithmPython algorithm
Python algorithm
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
Code optimization
Code optimizationCode optimization
Code optimization
 
use case point estimation
use case point estimationuse case point estimation
use case point estimation
 
Object Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsObject Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of Exams
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
Csci360 08-subprograms
Csci360 08-subprogramsCsci360 08-subprograms
Csci360 08-subprograms
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
 
Code optimization
Code optimizationCode optimization
Code optimization
 
Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoring
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
 
10 implementing subprograms
10 implementing subprograms10 implementing subprograms
10 implementing subprograms
 

Andere mochten auch

University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs emailhccit
 
Notes5
Notes5Notes5
Notes5hccit
 
Week03
Week03Week03
Week03hccit
 
Week04
Week04Week04
Week04hccit
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013hccit
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12hccit
 
Notes2
Notes2Notes2
Notes2hccit
 

Andere mochten auch (7)

University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
 
Notes5
Notes5Notes5
Notes5
 
Week03
Week03Week03
Week03
 
Week04
Week04Week04
Week04
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
 
Notes2
Notes2Notes2
Notes2
 

Ähnlich wie Week05

Week10style
Week10styleWeek10style
Week10stylehccit
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamedMd Showrov Ahmed
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxVigneshkumar Ponnusamy
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDeepikaV81
 
Java method
Java methodJava method
Java methodsunilchute1
 
14method in c#
14method in c#14method in c#
14method in c#Sireesh K
 
OOP Using Java Ch2 all about oop .pptx
OOP Using Java Ch2  all about oop  .pptxOOP Using Java Ch2  all about oop  .pptx
OOP Using Java Ch2 all about oop .pptxdoopagamer
 
MPI - 2
MPI - 2MPI - 2
MPI - 2Shah Zaib
 
intro to c
intro to cintro to c
intro to cteach4uin
 
Week12
Week12Week12
Week12hccit
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab neweyavagal
 
Week02
Week02Week02
Week02hccit
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptMahyuddin8
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptghoitsun
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptxVAIBHAVKADAGANCHI
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newLast7693
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newscottbrownnn
 
C Introduction
C IntroductionC Introduction
C IntroductionSudharsan S
 

Ähnlich wie Week05 (20)

Week10style
Week10styleWeek10style
Week10style
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Java method
Java methodJava method
Java method
 
14method in c#
14method in c#14method in c#
14method in c#
 
OOP Using Java Ch2 all about oop .pptx
OOP Using Java Ch2  all about oop  .pptxOOP Using Java Ch2  all about oop  .pptx
OOP Using Java Ch2 all about oop .pptx
 
MPI - 2
MPI - 2MPI - 2
MPI - 2
 
UNIT-2-PPTS-DAA.ppt
UNIT-2-PPTS-DAA.pptUNIT-2-PPTS-DAA.ppt
UNIT-2-PPTS-DAA.ppt
 
intro to c
intro to cintro to c
intro to c
 
Week12
Week12Week12
Week12
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab new
 
Week02
Week02Week02
Week02
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab new
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab new
 
C Introduction
C IntroductionC Introduction
C Introduction
 

Mehr von hccit

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syllhccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guidehccit
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014hccit
 
Photoshop
PhotoshopPhotoshop
Photoshophccit
 
Flash
FlashFlash
Flashhccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overviewhccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochurehccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exerciseshccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questionshccit
 
Movies questions
Movies questionsMovies questions
Movies questionshccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questionshccit
 
Section b
Section bSection b
Section bhccit
 
B
BB
Bhccit
 
A
AA
Ahccit
 
Section a
Section aSection a
Section ahccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mjhccit
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqhccit
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mjhccit
 

Mehr von hccit (20)

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
 
Photoshop
PhotoshopPhotoshop
Photoshop
 
Flash
FlashFlash
Flash
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
 
Movies questions
Movies questionsMovies questions
Movies questions
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
 
Section b
Section bSection b
Section b
 
B
BB
B
 
A
AA
A
 
Section a
Section aSection a
Section a
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedq
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mj
 

KĂźrzlich hochgeladen

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

KĂźrzlich hochgeladen (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Week05

  • 2. Copyright Warning COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been copied and communicated to you by or on behalf of Bond University pursuant to Part VB of the Copyright Act 1968 (the Act). The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under the Act. Do not remove this notice. Š 2004 Pearson Addison-Wesley. All rights reserved 5-2
  • 3. Software Construction • As programs become larger, they become more complicated  more variables, more loops, more nested structures • We need ways to isolate this complexity • All computer languages provide mechanisms to do this, e.g.  methods, classes, packages, libraries, whole programs • This week, we are going to look at methods Š 2004 Pearson Addison-Wesley. All rights reserved 5-3
  • 4. Methods • A method is a “mini-program”, with its own variables and lines of code • It usually get input by means of variables which are passed to it • The method can return one value, which is the result of the “mini-program” • From the caller's point of view, the method is a black box which performs some work, e.g answer= generator.nextInt(MAX); Š 2004 Pearson Addison-Wesley. All rights reserved 5-4
  • 5. Some You Have Seen Already • You have already used methods. Some take input but provide no outputs, e.g  System.out.print(“hello”);  System.out.println(“hello”); • Some methods take no input but return a value, e.g.  guess= scan.nextInt();  name= scan.nextLine(); • Some take no inputs, and return nothing, e.g  public static void main(); • Taking input is optional, and so is returning a value. • It's up to the designer of the method to decide what is required to make the method work Š 2004 Pearson Addison-Wesley. All rights reserved 5-5
  • 6. Why Methods? • Methods help to isolate complexity: code to do a certain task is contained within a method • Methods allow you to think in terms of “components”:  get user input, print out a header, determine if a number is valid  once you have written a method and tested that it is correct, you can use it as a black box component • Methods enforce the DRY Principle: don't repeat yourself.  If you write the same code twice, bad. Why?  Convert it into a method, then call the method multiple times • Methods can be tested. This helps to prove that your components work correctly Š 2004 Pearson Addison-Wesley. All rights reserved 5-6
  • 7. Your First Method • Let's write a method to find the biggest of two numbers. • What inputs does it require?  two integers • Does it need to return a value?  Yes, the value of the biggest number • OK, let's call the two integers a and b • We can write some of the Java code now: if (a>b) // then a is bigger, return its value else // b is bigger, return it instead Š 2004 Pearson Addison-Wesley. All rights reserved 5-7
  • 8. The return keyword • The return keyword is used to return a value out of a method. We can modify our code: if (a>b) return(a); else return(b); • Note: the return ends the execution of the method. If we return(a), then the code from else onwards will not get executed • All return()s in a method must return the same type of data. Here, we always return an int Š 2004 Pearson Addison-Wesley. All rights reserved 5-8
  • 9. Declaring the Method • We must now declare the method. This tells the other Java code how to use the method and what it will return  The method's name is maxOf  It takes two integers as input  It returns a single int value public static int maxOf(int a, int b) { if (a>b) return(a); else return(b); } Š 2004 Pearson Addison-Wesley. All rights reserved 5-9
  • 10. Trying It Out With Bluej • Let's try the code out in Bluej  Open a new program, note that it already comes with a method called main()  Add the maxOf() code after the code for main()  Compile the program • Now right-click on the file. You will see • 2004 Pearson Addison-Wesley.maxOf() method Š Select the All rights reserved 5-10
  • 11. Trying It Out With Bluej • Bluej will provide you with a window to enter the input values to the method • Enter two values and click OK • Bluej runs the method, and shows you the result returned by the method Š 2004 Pearson Addison-Wesley. All rights reserved 5-11
  • 12. Calling a Method • Now it's time to call the method with real Java code. Modify the main() method to have this code: int num1, num2, result; num1= 76; num2= 3004; result= maxOf(num1, num2); System.out.println(“The result is” + num1); System.out.println( maxOf(2, 17-8) ); • Try to guess what will get printed out when the main() method is run Š 2004 Pearson Addison-Wesley. All rights reserved 5-12
  • 13. Terminology • The list of variables that are the inputs to a method are known as its formal parameters  int maxOf(int a, int b) a & b are formal parameters • The values that are used when a method is called are its actual parameters, or its arguments result= maxOf(2, 17-9); 2 and 17-9 are the arguments • The values of the arguments are calculated, and copies of these values are assigned into the formal parameters when the method is called Š 2004 Pearson Addison-Wesley. All rights reserved 5-13
  • 14. Call by Value • Copying the values of the arguments into a method is known as call by value result= maxOf(2, 17-9); maxOf(int a, int b) return(...); • Similarly, the value returned by the method is copied back out the the caller of the method • The formal parameters, and any variables declared in the method are local variables • They are not visible outside the method Š 2004 Pearson Addison-Wesley. All rights reserved 5-14
  • 15. Methods are Expressions • Methods return a value. Therefore, they can be treated as expressions • You do not have to assign the result of a method call, e.g in main(): int num1, num2; System.out.print(“Enter a num: “); num1= scan.nextInt(); System.out.print(“Enter a num: “); num2= scan.nextInt(); System.out.println( 11 + maxOf(num1,num2) ); • If the user entered 50 and 61, the last line would calculate 11 + 61, and print out 72 Š 2004 Pearson Addison-Wesley. All rights reserved 5-15
  • 16. Designing Methods 1 • Methods are the basic components of any large program • With few exceptions, methods should  get their inputs as formal parameters, and return a result if required,  not print anything out to the user, and  not get any input from the user • The last 2 rules allow the caller of a method to decide if they want to print something out to the user • However, it is legal to write a method to prompt a user, get input and validate that input • Similarly, if user output is complicated, then it's OK to place the code in a method Š 2004 Pearson Addison-Wesley. All rights reserved 5-16
  • 17. Input Method Example public static double getHeight() { double userheight; Scanner scan = new Scanner (System.in); while (true) { System.out.print(“Enter your height: “); userheight= scan.nextDouble(); // Only accept if between 1.2m and 2.4m if ((userheight>=1.2) && (userheight<=2.4)) return(userheight); System.out.println(“Try again...”); } } Š 2004 Pearson Addison-Wesley. All rights reserved 5-17
  • 18. What's void? • We have to declare what type of value a method returns • What if it never returns a value? We declare it to return void, e.g. public static void printGrade(int mark) { if (mark<50) System.out.println(“FL”); else if (mark<65) System.out.println(“PS”); else if (mark<75) System.out.println(“CR”); else if (mark<85) System.out.println(“DN”); else System.out.println(“HD”); } Š 2004 Pearson Addison-Wesley. All rights reserved 5-18
  • 19. Methods Can Call Other Methods • Methods contain ordinary Java code; this code can call other methods • This has been shown in the examples on the previous slides, e.g  getHeight() called System.out.print() and scan.nextDouble() Š 2004 Pearson Addison-Wesley. All rights reserved 5-19
  • 20. Method Control Flow • When a method calls another method, execution of the program diverts into that method main doIt helpMe obj.doIt(); helpMe(); Š 2004 Pearson Addison-Wesley. All rights reserved 5-20
  • 21. Designing Methods 2 • The declaration of an a method is known as its interface • It describes how other methods use it • When designing large programs, cut the task up into sub-tasks, where a sub-task is done by one method • Design the interface to the method first:  what inputs does it need to do the job?  what result if any will it return? • Once you know what each method will do, then you can write the code for the method • This gives you a broad idea of the solution, before you have filled in the details Š 2004 Pearson Addison-Wesley. All rights reserved 5-21
  • 22. Design Time • As a class, design declarations for these methods: • A method to count the number of uppercase letters in a string • A method that, given a letter and a count, returns a string with that many of the letters • A method that indicates if a given number is a prime (true) or is not a prime (false) • A method to convert a Celsius temperature to Fahrenheit • A method that, given a string, indicates if the string has no uppercase letters in it • A method that, given a letter and a count, draws a box using that letter. Each side has count letters Š 2004 Pearson Addison-Wesley. All rights reserved 5-22
  • 23. Design Time 2 • Now, write the full method to count the number of uppercase letters in a string • Hint: Use the existing methods in the String class, especially length() and charAt() • Hint: You need to check out each letter, so you will need a loop. What type? • Hint: Do you know the length of the string? • Can you think of some inputs and outputs that will show if the method is working correctly? • Think of some very unusual strings to try out Š 2004 Pearson Addison-Wesley. All rights reserved 5-23
  • 24. Unit Testing • All large programs have bugs: usual estimate is 1 bug per 100 lines of code • Most bugs are logic bugs: the programmer thinks it works, but the code does something different • It's nearly impossible to tell if a program is 100% bug-free • Implication: programs should be tested thorougly to give assurance there are no bugs • Unit testing: test a method with a large set of inputs, to ensure that it produces the correct output • The test set is designed to stress the method as much as possible Š 2004 Pearson Addison-Wesley. All rights reserved 5-24
  • 25. Unit Testing • You should design the method interface first • THEN, construct a suitable test set for it • ONLY THEN, write the actual method code • Once you think you have written the method, you can then test the method with the unit tests • “Coding isn't complete until all the unit tests pass” • ALWAYS generate the tests by hand. Don't use a program to generate the test set. Why not? • Bluej provides a framework to construct unit tests. • You will see it in the labs, and you will be assessed on its use Š 2004 Pearson Addison-Wesley. All rights reserved 5-25