Transcript

Methods OR HOW TO MAKE A BIG PROGRAM SEEM SMALLER. Recall from last time If you have a big program, you can divide it up and develop it in pieces, testing each piece as you go along. Sometimes, we want to put the code into separate modules (in this case we will call them methods). Why? Some standard reasons Smaller is better (7 +- 2). Reuse Quality (which comes from reuse) Method terminology Void method Code that does something public static void doSomething( String text) doSomething(hello); This is the method call or invocation. This is the method definition. Examples weve seen: System.out.println(); Argument or actual parameter Corresponding formal parameter (or parameter) Method terminology Value returning method Code that does something return size; Code that does something return size; public static int doSomething( String text) int length; length = doSomething(hello); This is the method call or invocation. This is the method definition. Examples weve seen: formatter.format( ); Argument or actual parameter Corresponding formal parameter (or parameter) Method terminology Value returning method return size; public static int doSomething( String text) int length; length = doSomething(hello); This is the method call or invocation. This is the method definition. Examples weve seen: formatter.format( ); return type return statement Whats with the dots? System.out.println() keyboard.nextInt() Math.pow(5, 5) The name of the method always goes before the parameter list(parentheses). The names before the method name itself is the qualifier for the name. Qualified names Two kinds Name of a class, like Math or System. Name of an object of a class, like keyboard or out. A qualified name identifies where we can find the corresponding method. Static / non-static Methods that require an object (a specific instance) of a class are termed non-static. The Scanner methods are non-static and require a particular Scanner on which to operate. Methods that can be called by just the class name are called static (there is just one of them and they dont change). All of the Math class methods are static. Activity today Exercise 3 You will write void methods to sing Old MacDonald Had a Farm. The goal is to write the song with as few printlns as possible. But There are RULES Each team member must write at least one method (including main). Each line of text (including blank lines) must have its own System.out.println(). You may NOT join multiple lines of text using the \n character. You may NOT use loops, decisions, or other Java syntax we haven't yet covered in class. To simplify writing code by hand, you MAY abbreviate System.out.println as SOP. PA2 Is posted Its all about methods. Think about your PA1 and the repetition in it. We will build methods to simplify the code. Part A Stub out your program. Part B Write the code. Part C Reflection.


Top Related