1 / 35

CSCI 142

CSCI 142. Methods. Methods. You create a method by assigning a name to a chunk of code (group of statements) Benefits of Methods: Helps organize your code into logical sections You can call the same method multiple times Information hiding (hiding complexity). Method Flow Diagram.

kaycee
Download Presentation

CSCI 142

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. CSCI 142 Methods

  2. Methods • You create a method by assigning a name to a chunk of code (group of statements) • Benefits of Methods: • Helps organize your code into logical sections • You can call the same method multiple times • Information hiding (hiding complexity)

  3. Method Flow Diagram Call method Execute Method return Call method Execute Method return

  4. Pre-Built Methods We’ve already been using methods that have been provided for us. 

  5. Built-in Methods • In our previous examples we’ve been utilizing existing Java methods: • println() • readInt() • setFilled() • hidePen() • setSize()

  6. Parameter Passing • Notice that when you called the pre-built methods you passed in zero or more parameters, e.g: • println(“Hello World”); • readInt(“Type your number: ”); • setFilled(true); • hidePen(); • setSize(20, 30); • Parameters represent the data to be used in the method.

  7. Return Values • Some methods return data to the caller when they’re done executing • Examples int num1 = readInt(“Enter number: ”); double width = box.getWidth(); • A return value is data retrieved from a method • The return value, if there is one, essentially replaces the method call

  8. The APIs • The APIs tell us what parameters a method takes, and what it returns. Return Type Parameter(s)

  9. Information Hiding • We don’t know internally how Java wrote the println or readInt method. It’s pretty complex to write and retrieve data from the console. • Fortunately, we don’t need to know the details of how these methods were made because they’re wrapped up nicely for us in a method. • Information Hiding is useful as it helps to not overload the user with implementation details that don’t concern them.

  10. Creating Your own Methods Grouping your code into logical chunks

  11. run and init Methods • The run and init methods automatically execute when the program (Applet) starts • We don’t have to explicitly call these methods • init() executes before run()

  12. Making Our Own Method • Create a method called sayHello • Notice that it is parallel to the run method in terms of hierarchy

  13. Adding Content to Our Method • Currently our method is blank, let’s add content.

  14. Calling Our Method • We can call the method as many times as we want:

  15. Methods Calling Methods • A method can call another method

  16. Practice • Write a method called describeJava that prints "Java is great!" • Invoke the method from run()

  17. Parameters • I now want my program to say “Hi Joe” or Hi to whatever name I pass in • To have the method know what name you want to display you will pass a name (String) to the method as a parameter

  18. Parameters (…) • Notice you have to specify the type and name of the parameter • Then the parameter can be used like any other variable in the method type name

  19. Practice • Write another method called describeJava that accepts a String adjective, and prints "Java is adjective!" • Invoke the method from run(), and pass in your own adjective. • Invoke the method again, but with a different adjective.

  20. Another Example • Write a method that will take a price and display the total with tax

  21. Where’s the Answer? • When you run this, you see the answer displayed on the console, but the run method never gets the answer back. • What if the user had breakfast, lunch, then dinner, and wanted to get each of their totals and then calculate and display the grand total?

  22. Returning a Value • We use return so we can use the data we calculated in the method in our main body of code

  23. Specify Return Type • "void" means that a method doesn't return anything • If we want to return a value, we replace void with a return type • The return type is the data type of the return value • It can be a primitive type (e.g. int) or an object type (e.g. Color) • Here we are returning total which is a double

  24. Calling Multiple Times • We can call the method multiple times and store the return values in variables • Note that the variable type (e.g. lunchTotal) must match the return type

  25. Return Exits the Method • Notice that Java will not let you write any code after the return line • This is because ‘return’ exits the method, so nothing after it will be executed

  26. Practice • Write a method area that takes a width and a height, and returns the product of the two. • Invoke your method.

  27. More Complex Methods • The last two methods were very simple, but • Often we have control structures (if statements or loops) inside a method • It’s scenarios like this that make indenting your code very important

  28. Method with a for-loop • This method asks for a start and end count and then displays a list using a for loop

  29. Practice • Create a describeJava method that takes an adjective and a number, then prints "Java is adjective!" the given number of times. • For example, if I invoke describeJava("cool", 3), the method will print: Java is cool! Java is cool! Java is cool!

  30. Method with an if-statement • We will ask for the user's first and last name • We will then pass them to a canLogIn method which will: • Return true if the user's name matches my name • Otherwise, return false • Display the result

  31. Method with a if statement (…)

  32. Looking More Closely • Notice we return false with no else: We don’t need an else because if the code enters the if statement it will exit the method. So if it gets past the if then the name must not match.

  33. Practice • Create a method grade that takes a decimal between 0.0 and 4.0, and returns the corresponding letter grade, according to the following scale: • A 3.5-4.0 • B 3.0-3.5 • C 2.5-3.0 • D 2.0-2.5 • F <2.0 • If the user passes an invalid number, then it should return 'N'. • Test your method.

  34. Defining a Variable in a Method • This method sums the numbers from startCount to endCount

  35. Practice • Write a method calcSalary that accepts a number of hours worked and a pay rate. It should return the total pay, with overtime being compensated at time and a half. • Test your method.

More Related