1 / 45

CSCI1226 Introduction to Computing Science and Programming

CSCI1226 Introduction to Computing Science and Programming. Lecture 5: Methods Tami Meredith. Roadmap. The new material this week is predominantly from Chapter 5 (and Section 6.2 on static ) You should try and read Chapter 6 anyways

meraz
Télécharger la présentation

CSCI1226 Introduction to Computing Science and Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSCI1226Introduction to Computing Science and Programming Lecture 5: Methods Tami Meredith

  2. Roadmap • The new material this week is predominantly from Chapter 5 (and Section 6.2 on static) • You should try and read Chapter 6 anyways • Next class is a midterm review/summary with no new material (and lots of time for questions) • The midterm will cover Chapters 1 to 5 • After the midterm we will cover Chapter 7 (Arrays) and not too much more • The rest of the course will focus on learning to use what we've learned (repetition, practice, exercises)

  3. Textbook Summary

  4. Naming • I have a name so I can be identified and talked about • Entities encountered in programs are also named • In programming, we call a name an identifier • An identifier: • begins with a letter (a-z and A-Z) or underscore ('_') • is followed by any number of letters, underscores, and digits (0-9) • Examples: _var1, sum, main, String, charAt, my_total,addNums

  5. Things we name • Variables intsum = 0; • Methods (and their "parameters") public static void main (String args) {} • Classes public class myProgram {} • Arrays (We'll learn about these a bit later) int[] data_set = new int[256]; • We can name other things as well (as you may learn in advanced programming courses)

  6. Blocks of Code • A block of code is a group of statements that is considered as a single statement • Blocks can be used anywhere a single statement is expected: • Body of a loop • Then or else part of a conditional • Blocks are created by grouping a set of statements between the delimiters '{' and '}'

  7. Reuse • It is really useful to be able to reuse part of a program • The traditional technique in computing is to: • Group to the code to reuse • Name the code to reuse • Use the name to reference (i.e., call) the named group at any place we wish to reuse the code • We have been doing this already and you might not have noticed • Very simply, a method is a block of code with a name

  8. The Duality of Methods • Methods allow a block of code to be reused by naming the code • Methods have two different aspects • The method definition is where we assign the name to the code • A method call is where we use the block of code that we named (i.e., we "call" the method) • We can define a method and not use it (which is kind of a waste of time) • We MUST define a method that we use/call • We can use/call a method more than once!

  9. Example of Definition and Use public class test { // define the method printStuff public static void printStuff () { System.out.println("Hi there!"); } // end printStuff() public static void main (String[] args) { // call the method printStuff twice printStuff(); printStuff(); System.out.println("Done"); } // end main() } // end class test

  10. Method Calls • When a method is call, we jump to the beginning of the method • When a method completes, we jump back to where we were before the method was called • It is sort of like the body of the method being inserted where the call is located

  11. Control Flow Explanation 1Idea: jump to the body when a method is called public class test { // define the method printStuff public static void printStuff () { System.out.println("Hi there!"); } public static void main (String[] args) { // call the method printStuff printStuff(); printStuff(); System.out.println("Done"); } } // end class test

  12. Control Flow Explanation 2Idea: substitute the body for the call public class test { // define the method printStuff public static void printStuff () { System.out.println("Hi there!"); } public static void main (String[] args) { // printStuff();  Put a "copy" of the body here { System.out.println("Hi there!"); } // printStuff();  Put another "copy" of the body here { System.out.println("Hi there!"); } System.out.println("Done"); } // end main() } // end class test

  13. The method main • We need a method called main because this is where the program begins • Rather than telling the computer where to begin, the process is simplified by always beginning at the start of the method called main • main (apart from being the starting point) is really just the same as any other method

  14. Exiting a program • There are 3 ways to exit a program • Execution ends normally when the end of main is reached • Execution ends any time there is a return inside main • Execution ends any time, in any method, when System.exit(n); occurs • n is the integer exit code • 0 if all is OK, can use other values to identify errors • OK for now to always use 0

  15. Data: In and Out • Data In • Some methods require data to operate • The data that are needed are called "parameters" Aside: data is plural, datum is singular • Data Out • Some methods generate new data that they wish to "give back" when they are done • The data that is generated is called the "return value"

  16. Example public class test { // Parameters are in RED // Arguments (to put in parameters) are in BLUE // define the method add3 – returns an int public static int add3 (intx, inty, intz) { return (x + y + z); // must be an int } // end add3() // define the method main – returns nothing, i.e., void public static void main (String[] args) { // call the method add3 int sum = add3(2, 4, 6); System.out.println("The sum is: " + sum); } // end main() } // end class test

  17. Example public class test2 { // Parameters are in RED // Arguments (to put in parameters) are in BLUE // define the method times2 – returns an int public static int times2 (intvalue) { return (2 * value); // must be an int } // end times2() // define the method main – returns nothing, i.e., void public static void main (String[] args) { // call the method add3 int x = times2(10); System.out.println("Two times 10 is " + x); } // end main() } // end class test2

  18. Data Flow

  19. Example 3. Body of times2 executes, valhas the value 10 public class test3 { public static int times2 (intval) { return (2 * val); } public static void main (String[] args) { int x = times2(10); System.out.println("Two times 10 is " + x); } } // end class test3 4. result, 20, is calculated and returned 1. Execution starts at main 2. 10 gets copied into location called val 5. return value of times2, 20, is stored in location x 6. printlnlooks up x and locates the value, 20, and prints it 7. end of main is reached, execution ends

  20. Method Definitions • Always have a "visibility" indicator (e.g., public) • Sometimes are declared as "static" • Always have a return type (which is "void" if the method returns nothing) • Always have a name • Always have a list of parameters in parentheses (but the list might be empty) • Always have a block of code public static voidmain(String[] a) { System.out.println("Hello World!"); }

  21. Return Statements • return causes a method to end • return usually has a value in parentheses after it, e.g., return(0); • the type of the value must match the "return type" of the method • if the method returns void, return is used without parentheses, e.g., return;

  22. Method Calls • Sometimes assign (or use) the return value • Sometimes indicate which classes/objects the method comes from • Always call the method by name • Provide values for the parameters int n = Scanner.nextInt(); System.out.println(); s.charAt(5);

  23. Why? • Methods permit us to reuse a block of code • Methods permit us to simplify code by replacing a complicated part with a meaningful name – we call this abstraction • Methods permit us to break difficult things into smaller (named) parts – this is referred to as decomposition • Methods permit us to hide the details of something – this is called information hiding

  24. Exercise • Write a method that: • is named compare • has two integers as parameters • returns • -1 if parameter1 > parameter2 • 1 if parameter2 > parameter 1 • 0 if they are equal

  25. Solution public static int compare (int p1, int p2) { if (p1 < p2) { return (1); } else { if (p1 > p2) { return (-1); } else { return (0); } } } // end compare()

  26. Exercise • Write a method that: • is named midpoint • has two integers as parameters • returns a floating point value that is halfway between the two parameters

  27. Solution public static float midpoint(int p1, int p2) { float result; result = ((float) (p1 + p2)) / 2.0f; return result; // An alternative would be: // return (((float) (p1+p2)) / 2.0f); } // end midpoint()

  28. Visibility • public • A method can be seen, and hence used, anywhere • Easiest and most convenient • Make everything public for now, until you learn about abstract data types • private • A method can only be used inside the class in which it is defined • Prevents the method being used in other classes when a program has more than one class • Used in abstract data types (ADTs) for information hiding

  29. Static • Something is static if it doesn't change • In Java, a static method is one that never moves (doesn't change location) because there is only ever one version of it • A static method is one that never references any external data • All it can access is its parameters and things it defines inside its block • Since we don't know how to reference external data, all our methods are static

  30. Terminology public class methods { // Parameters are in RED // Arguments (to put in parameters) are in BLUE // value is a parameter public static int times2 (intvalue) { return (2 * value); } // end times2() public static void main (String[] args) { // 10 is the argument that is assigned to the parameter int x = times2(10); // x stores the argument that is assigned to the parameter int y = times2(x); System.out.println("The result is " + y); } // end main() } // end class methods

  31. Calling Convention • Call by value • When an argument has a primitive type (e.g., int, float, boolean, char) the argument is COPIED and a COPY is stored in the parameter • Call by reference • When an argument has a composite type (e.g., string, array, class) the address (a reference) is COPIED and a COPY of the address is stored in the parameter • This can be very very confusing and irritating

  32. Example public class callby { // Pig-latinise a string public static void piggy (String s) { s = s.substring(1,s.length()) + s.substring(0,1); System.out.println("piggy: " + s); } // end piggy() // Driver to test method piggy() public static void main(String[] args) { String word = "programming"; System.out.println("main1: " + word); piggy(word); System.out.println("main2: " + word); } // end main() } // end class callby

  33. New Strings and Copies • The String methods (page 86) all say "Returns a new string having ..." • Thus, in the method piggy(), s (which contains a copy of the address of word) gets assigned new strings by substring() • NOTHING ever happens to the original word • When piggy returns, s is discarded and the new strings are discarded with it

  34. Swapping public static void swap (int x, int y) { int temp = x; x = y; y = temp; } int a = 7, b = 8; swap (a, b); // fails  • Why won't this work? Why is it impossible to write a method that swaps the values of two variables? • x and ystore copies of the value in a and b – the original locations (i.e., a, b) are only used to obtain the values (i.e., 7, 8) in the call to swap() • When swap() ends, x and ycease to exist and the copies they hold are discarded as well

  35. Exercise • Time for a little mental break ... something easy! • Write a method named max that takes 2 integer values and returns the largest of the 2 values • Hint: This isn't a trick question! It's not supposed to be hard! • Note: Return either value if they are equal

  36. Solution public static int max (int a, int b) { if (a > b) { return (a); } else { // b is returned if they are == as well return (b); } } // end max()

  37. User Input • It is very convenient to be able to get user input • Just like Java provides System.out to connect to the monitor, System.in is also provided to connect to the keyboard • System.in is not very useful on its own since it only reads a typeless byte stream • A scanner is a tool that breaks a stream of bytes into meaningful and useful parts and applies types (e.g., int, String) to those parts • See Section 2.5 and Figure 2.7 (Scanner Methods)

  38. Example import java.util.Scanner; public class echo { public static void main (String[] args) { String input; Scanner keyboard = new Scanner (System.in); do { input = keyboard.next(); System.out.println("You typed: " + input); } while (!input.equals("exit")); } // end main() } // end class echo

  39. Import • The class System is automatically instantciated inside the JVM, its always there for us! • Not much else is available however until we tell Java to go find it for us • import tells the JVM to load a library or class for us • import java.util.scanner; says look in the library named java.util and find the class Scanner, and then make it available so we can use it • Could also use import java.util.*; to get everything in the java.util library

  40. Exercise • Lets extend a previous idea by one step ... • Write a method named max3 that takes 3 integer values and returns the largest of the 3 values • This is a bit trickier and harder • THINK FIRST – make sure you know how to do this before you try to write Java code to do it!

  41. Solution public static int max3 (int a, int b, int c) { if (a > b) { // 1. either a or c if (a > c) { return (a); } else { return (c); } } else { // 2. either b or c if (b > c) { return (b); } else { return (c); } } }

  42. Alternative Solutions public static int max3 (int a, int b, int c) { // up to 6 tests needed if ((a >= b) && (a >= c)) return (a); if ((b >= a) && (b >= c)) return (b); if ((c >= a) && (c >= b)) return (c); } public static int max3 (int a, int b, int c) { if ((a >= b) && (a > c)) { return (a); } else if (b >= c) { return (b); } return (c); }

  43. Dare we? • Lets extend this idea by yet one more step ... • Write a method named max4 that takes 4 integer values and returns the largest of the 4 values • This is a LOT trickier and harder • THINK FIRST – make sure you know how to do this before you try to write Java code to do it!

  44. Time for a break ... We'll come back to max4 after the midterm!

  45. To Do • Go to the lab and complete today's assignment • Read Chapter 5 as best you can – Its on methods, but its hard to read without understanding classes and objects • Try and read Chapter 6 on Objects, Classes, and Methods • You will need to read these several times to fully understand everything • Future lectures will go over more concepts for Object Oriented Programming

More Related