0
Week 5SoftwareConstruction:Methods
Copyright Warning               COMMONWEALTH OF AUSTRALIA                   Copyright Regulations 1969                    ...
Software Construction• As programs become larger, they become more  complicated        more variables, more loops, more n...
Methods• A method is a “mini-program”, with its own  variables and lines of code• It usually get input by means of variabl...
Some You Have Seen Already• You have already used methods. Some take input  but provide no outputs, e.g        System.out...
Why Methods?• Methods help to isolate complexity: code to do a  certain task is contained within a method• Methods allow y...
Your First Method• Lets write a method to find the biggest of two  numbers.• What inputs does it require?        two inte...
The return keyword• The return keyword is used to return a value out of  a method. We can modify our code:     if (a>b)   ...
Declaring the Method• We must now declare the method. This tells the  other Java code how to use the method and what it  w...
Trying It Out With Bluej• Lets try the code out in Bluej     Open a new program, note that it already comes with a      m...
Trying It Out With Bluej• Bluej will provide you with a window to enter the  input values to the method• Enter two values ...
Calling a Method• Now its time to call the method with real Java  code. Modify the main() method to have this  code:    in...
Terminology• The list of variables that are the inputs to a method  are known as its formal parameters        int maxOf(i...
Call by Value• Copying the values of the arguments into a  method is known as call by value  result= maxOf(2, 17-9);      ...
Methods are Expressions• Methods return a value. Therefore, they can be  treated as expressions• You do not have to assign...
Designing Methods 1• Methods are the basic components of any large  program• With few exceptions, methods should    get t...
Input Method Examplepublic static double getHeight(){  double userheight;  Scanner scan = new Scanner (System.in);     whi...
Whats void?• We have to declare what type of value a method  returns• What if it never returns a value? We declare it to  ...
Methods Can Call Other Methods• Methods contain ordinary Java code; this code  can call other methods• This has been shown...
Method Control Flow• When a method calls another method, execution of  the program diverts into that method               ...
Designing Methods 2• The declaration of an a method is known as its  interface• It describes how other methods use it• Whe...
Design Time• As a class, design declarations for these methods:• A method to count the number of uppercase  letters in a s...
Design Time 2• Now, write the full method to count the number of  uppercase letters in a string• Hint: Use the existing me...
Unit Testing• All large programs have bugs: usual estimate is 1  bug per 100 lines of code• Most bugs are logic bugs: the ...
Unit Testing•    You should design the method interface first•    THEN, construct a suitable test set for it•    ONLY THEN...
Upcoming SlideShare
Loading in...5
×

Week05

224

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
224
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Week05"

  1. 1. Week 5SoftwareConstruction:Methods
  2. 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. 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. 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 callers 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. 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.• Its 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. 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: dont 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. 7. Your First Method• Lets 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, lets 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. 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. 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 methods 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. 10. Trying It Out With Bluej• Lets 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. 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. 12. Calling a Method• Now its 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. 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. 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. 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. 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 its OK to place the code in a method© 2004 Pearson Addison-Wesley. All rights reserved 5-16
  17. 17. Input Method Examplepublic 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. 18. Whats 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. 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. 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. 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. 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. 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. 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• Its 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. 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 isnt complete until all the unit tests pass”• ALWAYS generate the tests by hand. Dont 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
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×