Presentation is loading. Please wait.

Presentation is loading. Please wait.

Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA 19383 CSC141 Computer Science I 9/17/20151.

Similar presentations


Presentation on theme: "Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA 19383 CSC141 Computer Science I 9/17/20151."— Presentation transcript:

1 Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA 19383 zjiang@wcupa.edu CSC141 Computer Science I 9/17/20151

2 Table of Contents Introduction (use of method) Declaring a method Calling a method Methods calling methods Control flow of method call Generalizing method Parameterization Multiple parameters Return values (vs. void) Recursive call Summary 29/17/2015

3 3 Procedural decomposition using methods 9/17/2015

4 4 public class FraggleRock { public static void main(String[] args) { System.out.println("Dance your cares away,"); System.out.println("Worry's for another day."); System.out.println("Let the music play,"); System.out.println("Down at Fraggle Rock."); System.out.println(); System.out.println("Dance your cares away,"); System.out.println("Worry's for another day."); System.out.println("Let the music play,"); System.out.println("Down at Fraggle Rock."); } } Redundancy in programs 9/17/2015

5 5 This is a space & timing problem: to locate the redundancy of any part of program running at any time. Compared with the timing problem in loop: 1 st, 2 nd, 3 rd … iterations Compared with the space problem in arrays: 1 st, 2 nd, 3 rd … elements 1 st, 2 nd, 3 rd … appearances of the same/similar procedure in your program! 9/17/2015

6 6 public class FraggleRock { public static void singChorus() { System.out.println("Dance your cares away,"); System.out.println("Worry's for another day."); System.out.println("Let the music play,"); System.out.println("Down at Fraggle Rock."); } public static void main(String[] args) { singChorus(); System.out.println(); singChorus(); } declaration, definition, body First time, four print lines repeated The second time, four prints repeated 9/17/2015

7 7 static method: A group of statements given a name. To use a static method: 1. define it(write down the recipe)‏ Write a group of statements and give it a name. 2. call it(cook using the recipe)‏ Tell our program to execute the method. 9/17/2015

8 8 public class FraggleRock { public static void singChorus() { System.out.println("Dance your cares away,"); System.out.println("Worry's for another day."); System.out.println("Let the music play,"); System.out.println("Down at Fraggle Rock."); } public static void main(String[] args) { singChorus(); System.out.println(); singChorus(); } Method body, declaration, definition Method call, 1 st time Method call, 2 nd time 9/17/2015

9 9 Declaring a static method The syntax for declaring a static method: public class {... public static void () { ; … ; } 9/17/2015

10 10 Calling a static method The syntax for calling a static method (cooking using the recipe): (); 9/17/2015

11 11 Declaring a static method public static void printAffirmation() { System.out.println("I am good enough!"); System.out.println("I am smart enough!"); System.out.println("People like me!"); } Calling a static method (possibly multiple times)‏ printAffirmation(); Output I am good enough! I am smart enough! People like me! I am good enough! I am smart enough! People like me! 9/17/2015

12 12 Methods calling methods One static method can call another: public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); } public static void message1() { System.out.println("This is message1."); } public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } Output: This is message1. This is message2. This is message1. Done with message2. Done with main. 9/17/2015

13 13 When a method is called, the execution "jumps" into that method executes all of the method’s statements "jumps" back to the statement after the method call Control flow of methods 9/17/2015

14 14 public class MethodsExample { public static void main(String[] args) { message1(); message2();... } public static void message1() { System.out.println("This is message1."); } public static void message2() { System.out.println("This is message2"); message1(); System.out.println("Done with message2."); } public static void message1() { System.out.println("This is message1."); } Output: This is message1. This is message2. This is message1. Done with message2. Done with main. 9/17/2015

15 15 Example: Figure drawing ______ / \ \ / \______/ \ / \______/ +--------+ ______ / \ | STOP | \ / \______/ ______ / \ +--------+ Write a program to print the figures. Use static methods to capture structure and and eliminate redundancy. 9/17/2015

16 16 Version 1: Unstructured ______ / \ \ / \______/ \ / \______/ +--------+ ______ / \ | STOP | \ / \______/ ______ / \ +--------+ Create an empty program with a skeletal header and main method. Copy the expected output into it, surrounding each line with System.out.println syntax. Run and verify that it produces the correct output. 9/17/2015

17 17 // Suzy Student, CSC 141, Autumn 2047 // This program prints several assorted figures. // public class Figures1 { public static void main(String[] args) { System.out.println(" ______"); System.out.println(" / \\"); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println(); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println("+--------+"); System.out.println(); System.out.println(" ______"); System.out.println(" / \\"); System.out.println("| STOP |"); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println(); System.out.println(" ______"); System.out.println(" / \\"); System.out.println("+--------+"); } 9/17/2015

18 18 Version 2: Structured with redundancy ______ / \ \ / \______/ \ / \______/ +--------+ ______ / \ | STOP | \ / \______/ ______ / \ +--------+ Identify the overall structure of the output, and divide the main method into several static methods based on this structure. 9/17/2015

19 19 ______ / \ \ / \______/ \ / \______/ +--------+ ______ / \ | STOP | \ / \______/ ______ / \ +--------+ Identify the overall structure of the output, and divide the main method into several static methods based on this structure. The structure of the output: initial "egg" figure second "teacup" figure third "stop sign" figure fourth "hat" figure This structure can be represented by methods: drawEgg drawTeaCup drawStopSign drawHat 9/17/2015

20 20 // Suzy Student, CSC 141, Autumn 2047 // Prints several assorted figures, with methods for structure. // public class Figures2 { public static void main(String[] args) { drawEgg(); drawTeaCup(); drawStopSign(); drawHat(); } // Draws a figure that vaguely resembles an egg. public static void drawEgg() { System.out.println(" ______"); System.out.println(" / \\"); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println(); } // Draws a figure that vaguely resembles a teacup. public static void drawTeaCup() { System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println("+--------+"); System.out.println(); } 9/17/2015

21 21 // Draws a figure that vaguely resembles a stop sign. public static void drawStopSign() { System.out.println(" ______"); System.out.println(" / \\"); System.out.println("| STOP |"); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println(); } // Draws a figure that vaguely resembles a hat. public static void drawHat() { System.out.println(" ______"); System.out.println(" / \\"); System.out.println("+--------+"); } 9/17/2015

22 22 Version 3: Structured without redundancy ______ / \ \ / \______/ \ / \______/ +--------+ ______ / \ | STOP | \ / \______/ ______ / \ +--------+ Further divide the program to eliminate all redundancy. 9/17/2015

23 23 Further divide the program to eliminate all redundancy. The redundancy: top half of egg (purple)‏ bottom half of egg (green)‏ divider line (yellow)‏ This redundancy can be fixed by methods: drawEggTop drawEggBottom drawLine ______ / \ \ / \______/ \ / \______/ +--------+ ______ / \ | STOP | \ / \______/ ______ / \ +--------+ 9/17/2015

24 24 // Suzy Student, CSC 141, Autumn 2047 // Prints several figures, with methods for structure and redundancy. public class Figures3 { public static void main(String[] args) { drawEgg(); drawTeaCup(); drawStopSign(); drawHat(); } // draws redundant part that looks like the top of an egg public static void drawEggTop() { System.out.println(" ______"); System.out.println(" / \\"); } // draws redundant part that looks like the bottom of an egg public static void drawEggBottom() { System.out.println("\\ /"); System.out.println(" \\______/"); } 9/17/2015

25 25 // Draws a figure that vaguely resembles an egg. public static void drawEgg() { drawEggTop(); drawEggBottom(); System.out.println(); } // Draws a figure that vaguely resembles a teacup. public static void drawTeaCup() { drawEggBottom(); System.out.println("+--------+"); System.out.println(); } // Draws a figure that vaguely resembles a stop sign. public static void drawStopSign() { drawEggTop(); System.out.println("| STOP |"); drawEggBottom(); System.out.println(); } // Draws a figure that vaguely resembles a hat. public static void drawHat() { drawEggTop(); System.out.println("+--------+"); } 9/17/2015

26 26 Exercise BBBBB B BBBBB B BBBBB AAAA A AAAAAA A N NNN N N AAAA A AAAAAA A N NNN N N AAAA A AAAAAA A Write a program to print the block letters spelling "banana". Use static methods to capture structure and and eliminate redundancy. 9/17/2015

27 27 Generalizing Method Consider the task of drawing the following figures: ************* ******* *********************************** ********** * ********** ***** * ***** The lines and figures are similar, but not exactly the same. 9/17/2015

28 28 public class Stars { public static void main(String[] args) { drawLineOf13Stars(); drawLineOf7Stars(); drawLineOf35Stars(); draw10x3Box(); draw5x4Box(); } public static void drawLineOf13Stars() { for (int i = 1; i <= 13; i++) { System.out.print("*"); } System.out.println(); } public static void drawLineOf7Stars() { for (int i = 1; i <= 7; i++) { System.out.print("*"); } System.out.println(); } public static void drawLineOf35Stars() { for (int i = 1; i <= 35; i++) { System.out.print("*"); } System.out.println(); }... Observation: Methods are redundant. Would constants help us solve this problem? Other ideas? 9/17/2015

29 29 What if we had the following? drawLine - A method to draw a line of any number of stars. drawBox - A method to draw a box of any size. main drawLine ******* 7 drawLine ************* 13 Character of each repetition General format of repetition 9/17/2015

30 30 Parameterization parameterized method: A method that is given extra information (e.g. number of stars to draw) when it is called. The common part of all calls in a generalization: 1 st, 2 nd, 3 rd, … parameter: A value passed to a method by its caller, mapping the difference of each call. Examples: System.out.println(“*”) or System.out.println(“**”) random.nextInt(10) 9/17/2015

31 31 Parameterized method declaration syntax: public static void ( ) { ; } The scope of the parameter is the entire method. Example: public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } } Whenever printSpaces is called, the caller must specify how many spaces to print. count ’s scope 9/17/2015

32 32 passing an argument for parameter: Calling a parameterized method and specifying a value for its parameter(s). Parameterized method call syntax: ( ); Example: System.out.print("*"); printSpaces(7); System.out.print("**"); int x = 3 * 5; printSpaces(x + 2); System.out.println("***"); Output: * ** *** 9/17/2015

33 33 When the parameterized method call executes: the value passed to the method is copied into the parameter variable the method's code executes using that value public static void main(String[] args) { printSpaces(7); printSpaces(13); } public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } 13 7 count: 9/17/2015

34 34 value semantics: When primitive variables (such as int or double ) are passed as parameters, their values are copied into the method's parameter variable. Modifying the method’s parameter variable will NOT affect the the variable which was passed to the method.... int x = 23; strange(x); System.out.println("2. x = " + x); // this x unchanged... } public static void strange(int x) { x = x + 1;// modifies my x System.out.println("1. x = " + x); } Output: 1. x = 24 2. x = 23 9/17/2015

35 35 ERROR: Not passing a parameter to a method that accepts parameters. printSpaces(); // ERROR: parameter value required ERROR: Passing a parameter of the wrong type. printSpaces(3.7); // ERROR: must be of type int The parameter must satisfy the domain of the method. 9/17/2015

36 36 Change the Stars program to use parameterized methods. public class Stars { public static void main(String[] args) { drawLineOf13Stars(); drawLineOf7Stars(); drawLineOf35Stars(); draw10x3Box(); draw5x4Box(); } public static void drawLineOf13Stars() { for (int i = 1; i <= 13; i++) { System.out.print("*"); } System.out.println(); } public static void drawLineOf7Stars() { for (int i = 1; i <= 7; i++) { System.out.print("*"); } System.out.println(); }... 9/17/2015

37 37 // Prints several lines of stars. // Uses a parameterized method to remove redundancy. public class Stars2 { public static void main(String[] args) { drawLine(13); drawLine(7); drawLine(35); } // Prints the given number of stars plus a line break. public static void drawLine(int count) { for (int i = 1; i <= count; i++) { System.out.print("*"); } System.out.println(); } 9/17/2015

38 38 Multiple parameters Methods can accept as many parameters as you like. When the method is called, it must be passed values for each of its parameters. Multiple parameters declaration syntax: public static void (,,..., ) { ; } Multiple parameters call syntax: (,,..., ); 9/17/2015

39 39 // Prints several lines and boxes made of stars. // Third version with multiple parameterized methods. public class Stars3 { public static void main(String[] args) { drawLine(13); drawLine(7); drawLine(35); System.out.println(); drawBox(10, 3); drawBox(5, 4); drawBox(20, 7); } // Prints the given number of stars plus a line break. public static void drawLine(int count) { for (int i = 1; i <= count; i++) { System.out.print("*"); } System.out.println(); } 9/17/2015

40 40 // Prints a box of stars of the given size. public static void drawBox(int width, int height) { drawLine(width); for (int i = 1; i <= height - 2; i++) { System.out.print("*"); printSpaces(width - 2); System.out.println("*"); } drawLine(width); } // Prints the given number of spaces. public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } 9/17/2015

41 41 Exercise public static void main(String[] args) { printNumber(4, 9); printNumber(17, 6); printNumber(8, 0); printNumber(0, 8); } Output: 444444444 171717171717 00000000 9/17/2015

42 42 public static void main(String[] args) { printNumber(4, 9); printNumber(17, 6); printNumber(8, 0); printNumber(0, 8); } Output: 444444444 171717171717 00000000 public static void printNumber(int number, int count) { for(int i=0; i<count; i++) { System.out.print(number); } System.out.println(); } 9/17/2015

43 43 Write a method named printDiamond that accepts a height as a parameter and prints a diamond figure. * *** ***** *** * Write a method named multiplicationTable that accepts a maximum integer as a parameter and prints a table of multiplication from 1 x 1 up to that integer times itself. 9/17/2015

44 44 Rewrite the following program to use parameterized methods: // Draws triangular figures of stars. public class Loops { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i - 1; j++) { System.out.print(" "); } for (int j = 1; j <= 10 - 2 * i + 1; j++) { System.out.print("*"); } System.out.println(); } for (int i = 1; i <= 12; i++) { for (int j = 1; j <= i - 1; j++) { System.out.print(" "); } for (int j = 1; j <= 25 - 2 * i; j++) { System.out.print("*"); } System.out.println(); } 9/17/2015

45 45 // Draws triangular figures using parameterized methods. public class Loops { public static void main(String[] args) { triangle(5); triangle(12); } // Draws a triangle figure of the given size. public static void triangle(int height) { for (int i = 1; i <= height; i++) { printSpaces(i - 1); drawLine(2 * height + 1 - 2 * i); } 9/17/2015

46 What does this code do? public static void main(String[] args) { int a = 7; int b = 35; System.out.println(a + " " + b); int temp = a; a = b; b = temp; System.out.println(a + " " + b); } 46 Parameter mystery (value vs. object) 9/17/2015

47 public static void main(String[] args) { int a = 7; int b = 35; System.out.println(a + " " + b); // swap a with b swap(a, b); System.out.println(a + " " + b); } public static void swap(int a, int b) { int temp = a; a = b; b = temp; } Does this work? Why or why not? 479/17/2015

48 Class type vs. primitive type When a primitive type of argument is passed for parameter, the value is copied. A method cannot change the value of an argument. When an object (or an array) is passed as a parameter, the object is not copied. The same object is referred to by both the original argument and the method's parameter. If a method is called on the parameter, it will affect the original object that was passed to the method. 489/17/2015

49 49 What is the output of the following program? public class Mystery { public static void main(String[] args) { int x = 5, y = 9, z = 2; mystery(z, y, x); System.out.println(x + " " + y + " " + z); mystery(y, x, z); System.out.println(x + " " + y + " " + z); } public static void mystery(int x, int z, int y) { x++; y = x - z * 2; x = z + 1; System.out.println(x + " " + y + " " + z); } x: y: z:x: z: y: 9/17/2015

50 50 Return Values (vs. Void) return: To send a value out as the result of a method, which can be used in an expression. A return value is like the opposite of a parameter. Parameters pass information in from the caller to the method. Return values pass information out from a method to its caller. How would this be useful? 9/17/2015

51 51 Java has a class called Math that has several useful static methods to perform mathematical calculations. logarithm base elog(value)‏ nearest whole numberround(value)‏ square rootsqrt(value)‏ random double between 0 and 1 random()‏ base to the exponent powerpow(base, exponent)‏ smaller of two valuesmin(value1, value2)‏ larger of two valuesmax(value1, value2)‏ logarithm base 10log10(value)‏ cosine, in radianscos(value)‏ absolute valueabs(value)‏ DescriptionMethod name 9/17/2015

52 52 Math method call syntax: Math. ( )‏ Examples: double squareRoot = Math.sqrt(121.0); System.out.println(squareRoot); // 11.0 int absoluteValue = Math.abs(-50); System.out.println(absoluteValue); // 50 System.out.println(Math.min(3, 7) + 2); // 5 Notice that the preceding calls are used in expressions; they can be printed, stored into a variable, etc… 9/17/2015

53 53 The Math methods do not print results to the console. Instead, each method evaluates to produce (or return) a numeric result, which can be used in an expression. main Math.abs -42 Math.round 2.71 42 3 9/17/2015

54 54 Evaluate the following expressions: Math.abs(-1.23)‏ Math.pow(3, 2)‏ Math.pow(10, -2)‏ Math.sqrt(121.0) - Math.sqrt(256.0)‏ Math.ceil(6.022) + Math.floor(15.9994)‏ Math.abs(Math.min(-3, -5))‏ Math.max and Math.min can be used to bound numbers. Consider an int variable named age. What statement would replace negative ages with 0? What statement would cap the maximum age to 40? 9/17/2015

55 55 Declaring a method that returns a value: public static ( ) { ; } Returning a value from a method: return ; Example: // Returns the given number cubed (to the third power). public static int cube(int number) { return number * number * number; } 9/17/2015

56 56 ERROR: Writing statements after a return statement. public static int increment(int x) { return (x + 1); x = x + 1;// ERROR: statement unreachable! } ERROR: Confusing the return variable with a variable in the calling method, AKA ignoring the return value. public class ReturnExample { public static void main(String[] args) { int x = 1; addOne(x); System.out.println("x = " + x); } public static int addOne(int x) { x = x + 1; return x; } 9/17/2015

57 57 Write a method called isFactor that accepts two integers as parameters, and returns true if the first is a factor of the second. 9/17/2015

58 58 Methods can return different values under different conditions: public static int min(int a, int b) { if (a > b) { return b; } else { return a; } public static String message(int place) { if (place == 1) { return "You won!"; } else { return "If you're not first, you're last!"; } 9/17/2015

59 59 public static int min(int a, int b) { if (a > b) { return b; } } The compiler will complain about a "missing return statement". Why? ERROR: Not returning a value in every path. In the above example, what if a <= b ? 9/17/2015

60 60 public static int min(int a, int b) { if (a > b) { return b; } else if (a <= b) { return a; } } It still produces the "missing return statement" error. Why? To our eyes, it is clear that all paths (greater, equal, less) do return a value. But the compiler thinks that if/else if code might choose not to execute any branch, so it refuses to accept this code. How can we fix it? 9/17/2015

61 61 Write a program that prompts the user for a maximum integer and prints out a list of all prime numbers up to that maximum. Here is an example log of execution: Maximum number? 50 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 15 total primes 9/17/2015

62 62 import java.util.*; public class PrintPrimes { public static void main(String[] args) { Scanner console = new Scanner(System.in); printPrimes(getNumber(console)); } public static int countFactors(int num) { int count = 0; for (int i = 1; i <= num; i++) { if (num % i == 0) { count++; } return count; }... 9/17/2015

63 63 public static int getNumber(Scanner console) { System.out.print("Maximum number? "); return console.nextInt(); } public static void printPrimes(int max) { int numPrimes = 0; if (max >= 2) { System.out.print(2); numPrimes++; for (int i = 3; i <= max; i++) { if (countFactors(i) == 2) { numPrimes++; System.out.print(", " + i); } System.out.println(); } System.out.println(numPrimes + " total primes"); } 9/17/2015

64 Recursive call Divide-and-conquer multi-layer job division (job becomes smaller) Results collection Result reporting (to caller)

65 f ( Job ) f ( Job.sub-job1 )f ( Job.sub-job2 ) f ( Job.sub-job1. sub-sub-job1 ) f ( Job.sub-job1. sub-sub-job2 )

66 Keys Division (The assignment and reporting of the requested job is divided into smaller pieces: job division, results collection, and result reporting, in divide-conquer tree by many non-leaf node.) Recursive procedure (ensure each node in the divide-conquer tree has similar procedure that can be written in a general/common format, but more abstract) Terminated condition (decide who will really do the job) Samples to see these keys (in static analysis)

67 Check the whole execution. Think about: You are a computer and run the program statement by statement. Need to check the result after each statement. Show the procedure called at different time.

68 f(int i) { if (i ==0) return 1; else return i*f(i-1); } 4*f(3)3*f(2)2*f(1)1*f(0) 1 1 2 624 f(4)? job divisionResults collection Result reporting Terminated condition General format, all same f(4)f(3)f(2)f(1)f(0)

69 f(int i) { if (i <=1) return 1; else return f(i-1)+f(i-2); } f(3)? f(2)+f(1)f(1)+f(0) 1 1 23 f(3)f(2)f(1)f(0)

70 f(int i) { int y=i; Static int z=0; z++; if (i <=1) { System.out.println(y+” ”+z); return 1; } else return f(i-1)+f(i-2); } f(3)? f(4)? f(2)+f(1) f(1)+f(0) 11 23 f(3)f(2)f(1)f(0) y=3 z=0 z=1 y=2 z=2 y=1 z=3 1 3 y=0 z=4 0 4 ? 1 f(1) y=1 z=5 1 5

71 f(int i) { if (i <=1) return 1; else if (i==3) return f(i-1)-f(i-2); else return f(i-1)+f(i-2); } f(3)? f(2)-f(1)f(1)+f(0) 11 21 f(3)f(2)f(1)f(0)


Download ppt "Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA 19383 CSC141 Computer Science I 9/17/20151."

Similar presentations


Ads by Google