1 / 21

CS 177

Week 9: Methods. CS 177. main() method. We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really long and hard to read Sometimes you need to do similar things several times:

lorin
Download Presentation

CS 177

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. Week 9: Methods CS 177

  2. main() method • We have written lots of code so far • It has all been inside of the main() method • What about a big program? • The main() method is going to get really long and hard to read • Sometimes you need to do similar things several times: • Read some input and check that it falls within certain values • Draw the same image at several different locations • Find the square root of several different numbers

  3. Idea of a method • Methods allow you to package some code to run over and over again • Methods usually take some input (like numbers or Strings) so that they can be parameterized • Methods often give back an answer (like the square root of a number) • Methods are called functions in some other languages

  4. Advantages of methods • More modular programming • Break a program into separate tasks • Each task could be assigned to a different programmer • Code reusability • Use code over and over • Could be in a code library (like Math.sqrt()) • Less code duplication • Improved readability • Each method can do a few, clear tasks

  5. Anatomy of a method Type of 1st argument Type of last argument Type of answer Required syntax public static type name(type arg1,…,type argn) { statement1; statement2; … statementm; } Name of 1st argument Name of last argument Name of method Code done by method

  6. Simple method example • Given two integers, find the smaller: • public static intmin(int a, int b) • { • if( a < b ) • return a; • else • return b; • }

  7. Why static? • static methods are methods that are not connected to a particular type of object • They are just supposed to perform some simple task • We are going to focus on static methods until next week • For now, the definition of every method will include the static keyword

  8. Value returning methods • It is possible to divide methods into two types: • Value returning methods • Void methods • Value returning methods return an answer: int small =min(x, y);

  9. Void methods • Void methods are declared with void as their return type • Void methods just do something • If you try to save the value they give back, there will be an error public static void help(int times) { for( inti = 1; i<= times; i++ ) System.out.println(“Help!”); return; }

  10. return statements • Like most code in Java, the code inside a method executes line by line • Of course, you are allowed to put conditionalstatements and loops inside methods • You can also put in return statements • A method will stop executing and jump back to wherever it was called from when it hits a return • The return statement is also where you can put a value that will be given back to the caller

  11. Calling methods • Defining a method is only half the fun! • You have to call methods to use them • Calling a method means giving a method the parameters (or arguments) it needs and then waiting for its answer • By now, you have done many method calls • System.out.println() • Math.sqrt() • You can call your own methods the same way

  12. Calling syntax • Proper syntax for calling a static method is first the name of the class that the method is in, a dot, the name of the method, then the arguments • If the method is in the same class as the code calling it, you can leave off the Class. part • If it is a value returning method, you can store that value into a variable of the proper type Class.name(arg1, arg2, arg3);

  13. Scope • Variables from outside of the method don’t exist unless they have been passed in as parameters • No matter how complex a program is, inside this method only x, y, and z variables exist • public static intadd(int x, int y) • { • int z = x + y; • return z; • }

  14. Binding • A magical process called binding happens which copies the values from the calling code into the parameters of the method • The calling code can use variables with the same names, with different names, or even just literals (like 3 or 2.6758) • The method does not change the values of the variables in the original code • Remember it only has copies of the values

  15. Binding example inta = 10; int x = 3; int y = add( 5, a ); //y contains 15 now • No connection between the two different x’s and y’s • public static intadd(intx, inty){ • int z = x + y; //5 + 10 • return z; • }

  16. Static method rules • Start a method with the keywords public static • Next comes the return type • Then the name of the method • Then, in parentheses, the arguments you want to give to the method • Inside braces, put the body of the method • Include a return statement that gives back a value if it is that type of method

  17. Distance • Finding the Euclidean distance between two points is very important • There are applications in: • Route planning • Graphic design software • Video games • Let’s make a method • Formula:

  18. method euclid() • No matter how complex a program is, inside this method, only x, y, and z variables exist • public static double euclid (double x1, double x2, doubley1, doubley2) • { • doublexsq= (x1-x2)*(x1-x2); • doubleysq= (y1-y2)*(y1-y2); • doubled = Math.sqrt(xsq+ysq); • returnd; • }

  19. Conway’s Game of Life • A cell is represented by a block in a grid • Each cell has 8 neighbors • Simple rules for a cell “coming to life” or “dying”: • A live cell with fewer than 2 live neighbors dies from loneliness • A live cell with more the 3 live neighbors dies from overcrowding • A live cell with exactly 2 or 3 neighbors keeps living • A dead cell with exactly 3 neighbors comes to life

  20. method conway() • public static void conway (int[][] cell, int m, int n) • { • int live = 0; • for (inti=m-1; i<=m+1; i++) • { • for (int j=n-1; j<=n+1; j++) • { • if (cell(i,j)==1) live++; • } • } • No matter how complex a program is, inside this method, only x, y, and z variables exist

  21. method conway() (cont.) • if (cell(m,n)==1) • { • live--; • if (live < 2 || live > 3) • cell(m,n) = 0; • } • else • { • if (live == 3) • cell (m,n) = 1; • } • return; • } • No matter how complex a program is, inside this method, only x, y, and z variables exist

More Related