350 likes | 495 Views
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.
E N D
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 Call method Execute Method return Call method Execute Method return
Pre-Built Methods We’ve already been using methods that have been provided for us.
Built-in Methods • In our previous examples we’ve been utilizing existing Java methods: • println() • readInt() • setFilled() • hidePen() • setSize()
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.
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
The APIs • The APIs tell us what parameters a method takes, and what it returns. Return Type Parameter(s)
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.
Creating Your own Methods Grouping your code into logical chunks
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()
Making Our Own Method • Create a method called sayHello • Notice that it is parallel to the run method in terms of hierarchy
Adding Content to Our Method • Currently our method is blank, let’s add content.
Calling Our Method • We can call the method as many times as we want:
Methods Calling Methods • A method can call another method
Practice • Write a method called describeJava that prints "Java is great!" • Invoke the method from run()
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
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
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.
Another Example • Write a method that will take a price and display the total with tax
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?
Returning a Value • We use return so we can use the data we calculated in the method in our main body of code
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
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
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
Practice • Write a method area that takes a width and a height, and returns the product of the two. • Invoke your method.
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
Method with a for-loop • This method asks for a start and end count and then displays a list using a for loop
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!
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
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.
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.
Defining a Variable in a Method • This method sums the numbers from startCount to endCount
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.