1 Review Quisioner Kendala: Kurang paham materi. Praktikum Pengaruh teman
Lecture 5: Functional decomposition
Prepared by: Ms Sandy Lim
BIT106 Introduction to Programming in Java
3
The Math class
We can use pre-defined methods from the 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
5
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.
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 purpose or function.
The main method will then be kept at a reasonable size.
7
Advantages of using methods
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
8
Using Methods in Programs
When we use methods, the main method acts as a coordinator
Particular methods are called or invoked as the need arises.
The computer passes the control to the method when the method is called.
9
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
10
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 typemethod name
parameter list
method bodymethod header
11
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)
12
Access Modifiers
An access modifier indicates how a method can be accessed: public private protected static
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.
13
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.
14
Example
Consider the following static method:
public static void printStars(){
System.out.println("***********************");}
static keyword used
void return typeindicates no value will be returned
15
Example – method invocation
public class Star{
public static void main(String[] args){
System.out.println("Here is a line of stars");printStars();System.out.println("Here is another!");printStars();
}
public static void printStars(){
System.out.println("***********************");}
}
static keyword usedvoid return typeindicates no value will be returned
method invoked here
and here
16
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.
public class PrintName{
public static void main(String[] args){
System.out.println("My name is Jane!");Star.printStars();
}}
The static method printStars() is found in the class Star
17
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)
18
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:
public static void greeting(char gender, String name)
Which statement can be used to invoke this method?
greeting("m", "Joe");greeting("Jane", 'f');greeting("Joe");greeting('f', "Joe");
19
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.
20
Exercise
Using the two methods printStars() and printStars(n), available in the Star class, write a program that will print the following:
Starting************************************
**********
Finished:*************************************
21
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?
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 invocationis 15.
bigger gets the value that is returned
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 valuemust be a double
24
Void Return Type
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?");}
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 itemSystem.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);
public static double cost(double uPrice, int qty){
return uPrice * qty;}
invocations:
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.
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 should return a letter grade based on the table:
Place both methods in a class named Result and test them.
28
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 LimEnter your assignment score :60Enter your exam score :90
FINAL RESULTSName Assignment Exam Total GradeMargaret Lim 60.0 90.0 81.0 A
Press any key to continue...