1 Review Quisioner Kendala: Kurang paham materi. Praktikum Pengaruh teman.

Slides:



Advertisements
Similar presentations
Review pages for the AP CS Exam
Advertisements

Escape Sequences \n newline \t tab \b backspace \r carriage return
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
1001ICT Programming 1 Semester 1, 2011 Lecture 6 Using Java Classes (Textbook, Chapter 3, Sections 3.2 to 3.7 ONLY)
Using Matrices in Real Life
Chapter 6: User-Defined Functions I
Final and Abstract Classes
Basic Java Constructs and Data Types – Nuts and Bolts
Classes and Objects in Java
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Chapter 4 Parameters and Overloading. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Learning Objectives Parameters Call-by-value Call-by-reference.
Chapter 1 The Study of Body Function Image PowerPoint
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Year 6 mental test 5 second questions
Year 6 mental test 10 second questions
Introduction to arrays Array One dimenstional array.
Introduction to Programming
4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.
Lecture 10 Flow of Control: Loops (Part 2) COMP1681 / SE15 Introduction to Programming.
© Vinny Cahill 1 Writing a Program in Java. © Vinny Cahill 2 The Hello World Program l Want to write a program to print a message on the screen.
Chapter 7: Arrays In this chapter, you will learn about
Data Structures ADT List
ABC Technology Project
Programming Methodology (1). public class Hello { public static void main(String[] args) { System.out.println("Hello world"); } } Hello world.
ITP © Ron Poet Lecture 4 1 Program Development. ITP © Ron Poet Lecture 4 2 Preparation Cannot just start programming, must prepare first. Decide what.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
Lilian Blot PART III: ITERATIONS Core Elements Autumn 2012 TPOP 1.
© 2012 National Heart Foundation of Australia. Slide 2.
1 User-Defined Classes The String class is a pre-defined class that is provided by the Java Designer. Sometimes programmers would like to create their.
1 Arrays An array is a special kind of object that is used to store a collection of data. The data stored in an array must all be of the same type, whether.
Lets play bingo!!. Calculate: MEAN Calculate: MEDIAN
Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
1 Variables and Data Types. 2 Variable Definition a location in memory, referenced by a name (identifier), where data of a given type can be stored, changed,
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
25 seconds left…...
Chapter Three Arithmetic Expressions and Assignment Statements
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 10 – Enhancing the Wage Calculator Application:
Types of selection structures
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
© 2007 Lawrenceville Press Slide 1 Chapter 5 The if Statement  Conditional control structure, also called a decision structure  Executes a set of statements.
We will resume in: 25 Minutes.
Chapter 2 JAVA FUNDAMENTALS
Computer Programming Lab(7).
PSSA Preparation.
Java Math Class. What is the Math Class? The Math Class is another class that is prepared by Java for us to use We use this class for mathematical operations.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 13 – Salary Survey Application: Introducing.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 7 User-Defined Methods.
Chapter 6: User-Defined Functions I
Object Oriented Systems Lecture 03 Method
Presentation transcript:

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. MethodReturn type ExampleMeaning 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)doubledouble value = Math.pow(2, 3) value  2^3 or 8.0 Math.round(num)longlong rounded1 = Math.round(2.16) long rounded2 = Math.round(2.87) rounded1  2 rounded2  3 Math.sqrt(num)doubledouble sqrt1 = Math.sqrt(9) sqrt1   9 or 3

4 Review Try each of the pre-defined methods from the Math class listed on the previous slide

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 type method name parameter list method body method 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 type indicates 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 used void return type indicates 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 invocation is 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 returned the returned value must 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 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); 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 D 50  total < 60 C 60  total < 70 B 70  total < 80 A 80  total  100 GradeRange The 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 Lim Enter your assignment score :60 Enter your exam score :90 FINAL RESULTS Name Assignment Exam Total Grade Margaret Lim A Press any key to continue...