Method / Fungsi
Method / Fungsi
Method / Fungsi
Kendala:
Kurang paham materi. Praktikum Pengaruh teman
We can use pre-defined methods from the Math class to perform calculations.
Return type Example Meaning
Method
Math.abs(num)
Math.max(num1, num2) Math.min(num1, num2)
int / double
int / double int / double
pValue |-5| or 5
larger 6 bigger 2.3 min 1 small 5.16
Math.pow(num1, num2)
Math.round(num)
double
long
Math.sqrt(num)
double
sqrt1 9 or 3
3
Review
Try each of the pre-defined methods from the Math class listed on the previous slide
Review
Write a Java program that asks the user to enter two numbers, then find the absolute value each of the numbers. Then find square root of the larger of the two positive numbers.
Functional Decomposition
When our programs become larger, we may want to break them down into parts. This is done by using separate, independent methods that have a specific purpose or function. The main method will then be kept at a reasonable size.
The main method is smaller and more readable Each method can be studied carefully and debugged separately Methods can be invoked (called) many times without duplication of code Methods can be modified without affecting other parts of the program Methods may even be used by other programs
Method Structure
A return type
indicates the type of data to be returned by the method indicates the purpose of the method indicates data that are input to the method contains the processing instructions for the method
A meaningful name
A body
Example
Here's a method that calculates and returns the total cost of an item given the unit price and quantity purchased
method name parameter list
return type
double calcCost(double uPrice, int qty) { double cost = uPrice * qty; return cost; } method header method body
10
Method Header
The method header is very important because it indicates the input output purpose of the method Can you determine the inputs, output and purpose of the following methods? double calcCost(double uPrice, int qty) boolean equalsIgnoreCase(String anotherString) double sqrt(double number) void displayErrorMessage() int largest(int a, int b, int c) String doSomething(char x, int y)
11
Access Modifiers
A public method indicates that it can be accessed from outside the class. If no access modifier is specified, the default will be public access.
12
Static methods
Static methods are methods which belong to a class and do not require an object to be invoked.
Some methods have no meaningful connection to an object. For example, finding the maximum of two integers computing a square root converting a letter from lowercase to uppercase generating a random number Such methods can be defined as static.
13
Example
14
and here
The static methods defined in one class can be invoked from another class. The name of the class where the method is defined must be used.
public class PrintName { public static void main(String[] args) { System.out.println("My name is Jane!"); Star.printStars(); } }
Arguments
Arguments or parameters provide inputs to a method. A method definition contains a formal argument list in the method header Arguments are defined with a type and a name and are separated by commas. Some methods may not receive any arguments.
double sqrt (double num) boolean login (String username, String password) char letterGrade(double examMark, int attendance)
17
A method invocation must correspond to the argument list of the method: number of arguments type of arguments order of arguments Example: A method has the following header:
public static void greeting(char gender, String name)
Overloading
We can create two methods in the Star class with the same name, printStars However, the method headers must be different:
public static void printStars() // this method prints a line of stars public static void printStars(int n) // this method prints a line of n stars
Creating two methods with the same name is called overloading. The method that is invoked will be based on the arguments. Consider the Math class methods.
19
Exercise
Using the two methods printStars() and printStars(n), available in the Star class, write a program that will print the following:
Starting ************************************ * ** *** **** Finished: *************************************
20
Exercise
Write down the definition of a Java method which calculates and displays the average score obtained by a student given three assignment scores. How do we call this method?
21
Methods are often used to process inputs (arguments). The results of this processing can be returned to the calling code (the code that invoked the method)
Return Types
double calcCost(double uPrice, int qty) { double cost = uPrice * qty; return cost; }
the returned value must be a double a value must be returned
23
If the return type in a method header is void, this means that the method does not return any values.
// This method simply prints out a greeting. public static void greeting(String name) { System.out.println("Hello," + name); System.out.println("How are you today?"); }
24
Data that is returned from a method can be: used directly in an expression, or stored in a variable Example: given the static method:
public static double cost(double uPrice, int qty) { return uPrice * qty; }
invocations:
double price = 2.50; // price per item System.out.println("The cost of 3 items " + cost(price, 3)); System.out.print("How many items do you want?"); int number = sc.nextInt(); double totalCost = cost(price, number); System.out.println("The cost of " + number + " items is "); System.out.println(totalCost);
25
Exercise
Write a method that receives input as an integer representing a time in minutes and returns a String representing the time in hours and minutes. Eg:
26
Exercise
Write two methods, calcTotal and findGrade. The first method should calculate and return the total based on two scores: assignment and exam. the assignment is worth 30% the exam is worth 70% find the total based on the weights The second method should return a letter grade based on the table:
Range 80 total 100 70 total < 80 60 total < 70 50 total < 60 < 50 Grade A B C D F
27
Exercise
Now use the methods you defined to write the following program: Ask a student for her name and assignment and exam scores, then display her results.
Enter your name :Margaret Lim Enter your assignment score :60 Enter your exam score :90
Assignment 60.0
Exam 90.0
Total 81.0
Grade A