1 / 60

Methods

Methods. Chapter 5 Spring 2007 CS 101 Aaron Bloomfield. Preparation. Scene so far has been background material and experience Computing systems and problem solving Variables Types Input and output Expressions Assignments Using objects Standard classes and methods

vcheek
Télécharger la présentation

Methods

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. Methods Chapter 5 Spring 2007 CS 101 Aaron Bloomfield

  2. Preparation • Scene so far has been background material and experience • Computing systems and problem solving • Variables • Types • Input and output • Expressions • Assignments • Using objects • Standard classes and methods • Decisions (if, switch) • Loops (while, for, do-while) • Next: Experience what Java is really about • Design and implement objects representing information and physical world objects

  3. Object-oriented programming • Basis • Create and manipulate objects with attributes and behaviors that the programmer can specify • Mechanism • Classes • Benefits • An information type is design and implemented once • Reused as needed • No need reanalysis and re-justification of the representation

  4. Known Classes • Classes we’ve seen • BigInteger • String • Rectangle • Vector • Scanner • System • Classes we’ll be seeing soon • BigDecimal • But the first step is on creating methods…

  5. Methods

  6. Methods we’ve seen • We’ve seen methods (functions) before • angleSin = Math.sin (90 * PI/180.0); • System.out.println (“Hello world”); • value = card.getBlackjackValue(); • We are going to start defining them • Note that many of these “return” a value • Math.sin() and card.getBlackjack() • The way to name methods is the same as variables • allTheWordsTogether • With the first letter of each word capitalized • Except the very first letter is lower case

  7. Our first class with methods public class Methods1 { public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt(); if ( value == 1 ) validValue(); else if ( value == 2 ) validValue(); else if ( value == 3 ) invalidValue(); else if ( value == 4 ) invalidValue(); else validValue(); } }

  8. Our first class with methods, continued public static void invalidValue() { System.out.println ("You have entered an invalid value."); System.out.println ("The program will now exit."); System.exit (0); } public static void validValue() { System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!"); System.out.println ("The program will now exit."); System.exit (0); }

  9. Program Demo • Methods1.java

  10. stdin 1 value Scanner What’s happening there public static void validValue() { System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!"); System.out.println ("The program will now exit."); System.exit (0); } public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt(); if ( value == 1 ) validValue(); // ... }

  11. Notes on these methods • At this point, all methods in the class are static • We will be discussing what static means later in this slide set • Until then, I’ll be ignoring it, and just telling you when things should and should not be static • Sorry! • None of those two methods return a value • Notice the “void” before the method name • And none take in any parameters • Notice the empty parameters after the method name

  12. A previous HW J3

  13. A revised HW 3 flowchart Green paths are “yes” paths, red are “no” paths We’ll make a slight modification to the diagram: Note that this part is repeated twice! Start over Revamping last semester’s HW J3 Cynical guru Start here Done tech support? Bitter yet? Successful managing? Promoted Become a coder Been a sysadmin? Hate people? Worked with NT? Start over Public danger Want to play w/nukes? Defense contractor

  14. The yellow boxed part is what was repeated from the previous slide if ( extractor.askUser(Q_TECH_SUPPORT) ){ if ( extractor.askUser(Q_BITTER_YET) ) if ( extractor.askUser(Q_MANAGEMENT) ) System.out.println (A_CYNICAL); else System.out.println (A_PROMOTED); else System.out.println (A_START_OVER); } else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){ if ( extractor.askUser(Q_HATE_PEOPLE) ) { System.out.println (A_CODER); } else if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR); else System.out.println (A_PUBLIC_DANGER); } else System.out.println (A_START_OVER); } else if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR); else System.out.println (A_PUBLIC_DANGER); } else System.out.println (A_START_OVER); HW J3 Code

  15. The yellow boxed part is what was repeated from the previous slide if ( extractor.askUser(Q_TECH_SUPPORT) ){ if ( extractor.askUser(Q_BITTER_YET) ) if ( extractor.askUser(Q_MANAGEMENT) ) System.out.println (A_CYNICAL); else System.out.println (A_PROMOTED); else System.out.println (A_START_OVER); } else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){ if ( extractor.askUser(Q_HATE_PEOPLE) ) { System.out.println (A_CODER); } else doBottomPartOfFlowchart(); } else doBottomPartOfFlowchart(); HW J3 Code with methods

  16. HW J3 Code with methods • The doBottomPartOfFlowchart method: public static void doBottomPartOfFlowchart() { if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR); else System.out.println (A_PUBLIC_DANGER); } else System.out.println (A_START_OVER); }

  17. What happened here • We took a common set of code • Wrote it once • But used it multiple times (twice in this case) • Granted, the code was a small segment (7 lines) • But, in other programs, could be very large • This is called Refactoring • It is an essential principle of software engineering • Has other names: factoring (notice there is no ‘re’ at the beginning), extracting a method, etc.

  18. Pros of Refactoring • Benefits of Refactoring • Reduce length of code • As you don’t have to repeat that section of code multiple times • Make code easier to read • The main if-else-if statement is shorter, thus easier to understand what’s going on • Changes are easier to make • If we want to modify that part of the flowchart, we only have to do it once • Rather than searching for each of the repeated code segments in a program

  19. Cons of Refactoring • Drawbacks of Refactoring • Because you are calling another method, it will be slightly slower • On the order of a few nanoseconds • Modern compilers can sometimes eliminate this penalty • The general consensus is that the benefits of Refactoring far outweigh the drawback(s)

  20. Return Values

  21. The return keyword • The return keyword immediately stops execution of a method • And jumps back to whatever called that method • And possibly returns a value (we’ll see this next) • Consider the following method public static void foo (int x) { if ( x == 1 ) return; System.out.println (“x is not 1”); } • This method will only print the String if x is not 1

  22. Return values • At some point in those methods, Java must be told to take a value and “pass” it back • Consider angleSin = Math.sin (90 * PI/180.0); • At some point in the Math.sin() method, the sin has been computed • And that value must be “passed back” to be stored in angle • Consider value = card.getBlackjackValue(); • At some point in the card.getBlackjackValue() method, the value has been computed • And that value must be “passed back” to be stored in value • This is called “returning” a value from a method • Note that some methods don’t return a value • System.out.println(), for example

  23. Return values (aka return types) public class Methods2 { public static int returnsAValue () { return 1; } public static double alsoReturnsAValue() { return 1.0; } public static void main (String args[]) { int value1 = returnsAValue(); System.out.println (value1); double value2 = alsoReturnsAValue(); System.out.println (value2); // The following line requires a cast int value3 = (int) alsoReturnsAValue(); System.out.println (value3); } }

  24. Program Demo • Methods2.java

  25. Return types • All a return statement does is take the value • Which could be a number • Or a value in a variable • Or an expression (such as x+1) • And “pass” it back to whatever called the method

  26. How well do you feel you understand return values? • Very well! This stuff is so easy. • With a little review, I’ll be good. • Not very well at all. • I’m so lost. What’s a return type again? • I’d rather not answer this question, thanks.

  27. Parameters • Sometimes you need to pass in parameters to tell a method how to perform • Consider Math.sin() – it needs to know the angle • The parameters are listed between the parenthesis after the method name • public static void main (String args[]) • The methods we will study next compute (and return) x2, x3, and x4

  28. The methods public static int square (int x) { int theSquare = x * x; return theSquare; } public static int cube (int x) { return x * x * x; } public static int fourthPower (int x) { return square(x) * square(x); }

  29. A method with multiple parameters public static int squareOrCube (int which, int value) { if ( which == 1 ) return value * value; else if ( which == 2 ) { int cube = value * value * value; return cube; } else return 0; }

  30. The main() method import java.util.*; public class Methods3 { // the previous methods go here public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter an int value"); int value = stdin.nextInt(); int theSquare = square(value); System.out.println ("Square is " + theSquare); System.out.println ("Cube is " + cube (value)); System.out.println ("Square is " + squareOrCube (1, value)); System.out.println ("Cube is " + squareOrCube (2,value)); System.out.println ("Fourth power is " + fourthPower (value)); } }

  31. Program Demo • Methods3.java

  32. name String courseName “CS 101” Returning objects • We can also return objects from methods • What gets returned is the reference to the object public class Methods4 { public static String getCourse () { String name = "CS 101"; return name; } public static void main (String args[]) { String courseName = getCourse(); System.out.println (courseName); } }

  33. Program Demo • Methods4.java

  34. Modifying parameters • Consider the following code public class Methods5 { public static void changeValue (int x) { x = 7; } public static void main (String args[]) { int y = 5; changeValue(y); System.out.println (y); } } • What gets printed?

  35. Program Demo • Methods5.java

  36. Pass by value • Java is a pass-by-value language • This means that a COPY of the parameter’s value is passed into the method • If a method changes that value, only the COPY is changed • Once the method returns, the copy is forgotten • And thus the change is not visible outside the method • There are other manners of returning values that are used in other languages • Pass by reference • Pass by name (nobody uses this anymore) • We will see about trying to change object parameters later in this slide set

  37. How well do you feel you understand parameters? • Very well! This stuff is easy! • Fairly well – with a little review, I’ll be good • Okay. It’s not great, but it’s not horrible, either • Not well. I’m kinda confused • Not at all. I’m soooooo lost

  38. Variable scoping • A variable is visible within the block it is declared • Called the “scope” of the variable public class Scoping { static int z public static void foo (int x) { // ... } public static void bar () { // ... } public static void main (String[] args) { int y; // ... } } This variable is visible anywhere in the Scoping class This parameter is visible only in the foo() method This local variable is visible until the end of the main() method

  39. How well do you feel you understand variable scoping? • Very well! This stuff is easy! • Fairly well – with a little review, I’ll be good • Okay. It’s not great, but it’s not horrible, either • Not well. I’m kinda confused • Not at all. I’m soooooo lost

  40. Method notes summary • You can put the methods in a class in any order • Java doesn’t care which one is listed first • Thus, you can call a method listed later in the method • This is different than C/C++ • All methods must specify a return type • If it’s void, then no value is returned • Parameters can’t be changed within a method • Although the objects that the parameters point to can be

  41. The 2005 Ig Nobel Prizes • Agricultural history • Physics • Medicine • Literature • Peace • Economics • Chemistry • Biology • Nutrition • Fluid dynamics “The Significance of Mr. Richard Buckley’s Exploding Trousers” The pitch drop experiment, started in 1927 Neuticles – artificial replacement testicles for dogs The 409 scams of Nigeria for a “cast of rich characters” Locust brain scans while they were watching Star Wars For an alarm clock that runs away, thus making people more productive “Will Humans Swim Faster or Slower in Syrup?” For cataloging the odors of 131 different stressed frogs To Dr. Yoshiro Nakamats who catalogued and analyzed every meal he ate for the last 34 years (and counting) “Pressures Produced When Penguins Pooh – Calculations on Avian Defaecation”

  42. More on parameter passing

  43. 5 5 7 y x x Modifying parameters • Consider the following code public class Methods5 { public static void changeValue (int x) { x = 7; } public static void main (String args[]) { int y = 5; changeValue(y); System.out.println (y); } } • What gets printed? • 5 is printed

  44. Program Demo • Methods5.java

  45. Pass by value • Java is a pass-by-value language • This means that a COPY of the parameter’s value is passed into the method • If a method changes that value, only the COPY is changed • Once the method returns, the copy is forgotten • And thus the change is not visible outside the method • There are other manners of returning values that are used in other languages • Pass by reference • Pass by name (nobody uses this anymore) • We will see about trying to change object parameters later in this slide set

  46. r rect Rectangle Rectangle - width = 1 - width = 10 - height = 2 - height = 20 + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth () + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth () Modifying parameters • Consider the following code import java.awt.*; public class Methods6 { public static void changeValue (Rectangle r) { r.setSize (10,20); } public static void main (String args[]) { Rectangle rect = new Rectangle(1, 2); changeValue(rect); System.out.println (rect.getWidth()); } } • What gets printed? • 10 is printed

More Related