Method / Fungsi

download Method / Fungsi

of 28

Transcript of Method / Fungsi

  • 7/30/2019 Method / Fungsi

    1/28

    1

    Review Quisioner

    Kendala:

    Kurang paham materi.

    Praktikum

    Pengaruh teman

  • 7/30/2019 Method / Fungsi

    2/28

    Lecture 5: Functional

    decomposition

    Prepared by: Ms Sandy Lim

    BIT106 Introduction toProgramming in Java

  • 7/30/2019 Method / Fungsi

    3/28

    3

    The Math class

    We can use pre-defined methods fromthe Math class to perform calculations.

    Method Return

    type

    Example Meaning

    Math.abs(num) int /

    double

    int pValue = Math.abs(-5) pValue |-5| or 5

    Math.max(num1, num2) int /

    double

    int larger = Math.max(5, 6)

    double bigger = Math.max(2.3, 1.7)

    larger 6

    bigger 2.3

    Math.min(num1, num2) int /

    double

    int min = Math.min(5, 1)

    double small =Math.min(5.16, 5.17)

    min 1

    small 5.16

    Math.pow(num1, num2) double double value = Math.pow(2, 3) value 2^3 or 8.0

    Math.round(num) long long rounded1 = Math.round(2.16)

    long rounded2 = Math.round(2.87)

    rounded1 2

    rounded2 3

    Math.sqrt(num) double double sqrt1 = Math.sqrt(9)

    sqrt1 9 or 3

  • 7/30/2019 Method / Fungsi

    4/28

    4

    Review

    Try each of the pre-defined methods fromthe Math class listed on the previous slide

  • 7/30/2019 Method / Fungsi

    5/28

    5

    Review

    Write a Java program that asks the user toenter two numbers, then find the absolute

    value each of the numbers. Then find

    square root of the larger of the two positivenumbers.

  • 7/30/2019 Method / Fungsi

    6/28

    6

    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 purposeor

    function.

    The mainmethod will then be kept at a

    reasonable size.

  • 7/30/2019 Method / Fungsi

    7/287

    Advantages of using methods

    The mainmethod is smaller and more readable

    Each method can be studied carefully and

    debugged separately

    Methods can be invoked (called) many timeswithout duplication of code

    Methods can be modified without affecting other

    parts of the program

    Methods may even be used by other programs

  • 7/30/2019 Method / Fungsi

    8/288

    Using Methods in Programs

    When we use methods, the mainmethod actsas a coordinator

    Particular methods are called orinvokedas

    the need arises.

    The computer passes the control to the

    method when the method is called.

  • 7/30/2019 Method / Fungsi

    9/289

    Method Structure

    A Java method has four parts: A return type

    indicates the type of data to be returned by the method

    A meaningful name

    indicates the purpose of the method An argument / parameter list

    indicates data that are input to the method

    A body contains the processing instructions for the method

    The method is organized into the method header

    the method body

  • 7/30/2019 Method / Fungsi

    10/2810

    Example

    Here's a method that calculates and returns the

    total cost of an item given the unit price and quantity

    purchased

    double calcCost(double uPrice, int qty)

    {

    double cost = uPrice * qty;return cost;

    }

    return type

    method name

    parameter list

    method bodymethod header

  • 7/30/2019 Method / Fungsi

    11/2811

    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 followingmethods?

    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)

  • 7/30/2019 Method / Fungsi

    12/2812

    Access Modifiers

    An access modifier indicates how a method can beaccessed: public

    private

    protected

    static

    A public method indicates that it can be accessedfrom outside the class.

    If no access modifier is specified, the default will bepublic access.

  • 7/30/2019 Method / Fungsi

    13/2813

    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.

  • 7/30/2019 Method / Fungsi

    14/2814

    Example

    Consider the following static method:

    publicstaticvoid printStars()

    {

    System.out.println("***********************");

    }

    static keyword used

    void return type

    indicates no value will be returned

  • 7/30/2019 Method / Fungsi

    15/2815

    Example method invocation

    publicclass Star

    {

    publicstaticvoid main(String[] args)

    {

    System.out.println("Here is a line of stars");

    printStars();

    System.out.println("Here is another!");

    printStars();

    }

    publicstaticvoid printStars()

    {System.out.println("***********************");

    }

    }

    static keyword usedvoid return type

    indicates no value will be returned

    method invoked here

    and here

  • 7/30/2019 Method / Fungsi

    16/2816

    Invoking from another class

    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.publicclass PrintName

    {

    publicstaticvoid main(String[] args)

    {

    System.out.println("My name is Jane!");Star.printStars();

    }

    }

    The static method printStars() is found in the class Star

  • 7/30/2019 Method / Fungsi

    17/2817

    Arguments

    Arguments or parameters provide inputs to a

    method.

    A method definition contains a formal argument

    list in the method headerArguments 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)

  • 7/30/2019 Method / Fungsi

    18/2818

    Invocation with arguments

    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:

    publicstaticvoid greeting(char gender, String name)

    Which statement can beused to invoke thismethod?

    greeting("m", "Joe");

    greeting("Jane", 'f');

    greeting("Joe");

    greeting('f', "Joe");

  • 7/30/2019 Method / Fungsi

    19/2819

    Overloading

    We can create two methods in the Star class with the samename, printStars

    However, the method headers must be different:

    public static void printStars()

    // this method prints a line of stars

    publicstaticvoid printStars(int n)

    // this method prints a line of n stars

    Creating two methods with the same name is calledoverloading.

    The method that is invoked will be based on thearguments.

    Consider the Math class methods.

  • 7/30/2019 Method / Fungsi

    20/2820

    Exercise

    Using the two methods printStars() andprintStars(n), available in the Star class,

    write a program that will print the following:

    Starting************************************

    *

    **

    *******

    Finished:

    *************************************

  • 7/30/2019 Method / Fungsi

    21/2821

    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?

  • 7/30/2019 Method / Fungsi

    22/28

    22

    Returning Data from Methods

    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)

    int bigger = Math.max(15, 6);

    System.out.print("The larger value is " + bigger);

    The result of this method invocation

    is 15.

    bigger gets the

    value that is

    returned

  • 7/30/2019 Method / Fungsi

    23/28

    23

    Return Types

    A method header must have a return type.

    double calcCost(double uPrice, int qty)

    {

    double cost = uPrice * qty;

    return cost;}

    return type is double

    a value must be returnedthe returned value

    must be a double

  • 7/30/2019 Method / Fungsi

    24/28

    24

    Void Return Type

    If the return type in a method header is void, thismeans that the method does not return any values.

    // This method simply prints out a

    greeting.publicstaticvoidgreeting(String name)

    {

    System.out.println("Hello," + name);

    System.out.println("How are youtoday?");

    }

  • 7/30/2019 Method / Fungsi

    25/28

    25

    Using Returned Data

    Data that is returned from a method can be: used directly in an expression, or

    stored in a variable

    Example: given the static method:

    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);

    publicstaticdouble cost(double uPrice, int qty)

    {

    return uPrice * qty;

    }

    invocations:

  • 7/30/2019 Method / Fungsi

    26/28

    26

    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: input: 415

    returned value: "6 hours 55 minutes"

    Write a program to test this method.

  • 7/30/2019 Method / Fungsi

    27/28

    27

    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

    F< 50

    D50 total < 60

    C60 total < 70

    B70 total < 80

    A80 total 100

    GradeRangeThe second method shouldreturn a letter grade based onthe table:

    Place both methods in a classnamed Result and test them.

  • 7/30/2019 Method / Fungsi

    28/28

    Exercise

    Now use the methods you defined to write the followingprogram:

    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

    FINAL RESULTSName Assignment Exam Total Grade

    Margaret Lim 60.0 90.0 81.0 A

    Press any key to continue...