CS305j Introduction to Computing Parameters and Methods 1 Topic 8 Parameters and Methods "We're flooding people with information. We need to feed it through.

Slides:



Advertisements
Similar presentations
Building Java Programs
Advertisements

1 MATH METHODS THAT RETURN VALUES. 2 JAVA'S MATH CLASS.
Return values.
BUILDING JAVA PROGRAMS CHAPTER 3 PARAMETERS AND OBJECTS.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
1 Parameters. 2 Repetitive figures Consider the task of drawing the following figures: ************* ******* *********************************** **********
Copyright 2008 by Pearson Education Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs Lecture 3-1: Parameters (reading: 3.1)
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Copyright 2008 by Pearson Education 1 Class constants and scope reading: 2.4 self-check: 28 exercises: 11 videos: Ch. 2 #5.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return; double ; System.out.printf reading: 3.2, 3.5, 4.4 videos: Ch.
CS305j Introduction to ComputingNested For Loops 1 Topic 6 Nested for Loops "Complexity has and will maintain a strong fascination for many people. It.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return; double ; System.out.printf reading: 3.2, 3.5, 4.4 videos: Ch.
Topic 10 return values, Math methods Based on slides bu Marty Stepp and Stuart Reges from " Thinking like a computer.
Topic 7 parameters Based on slides bu Marty Stepp and Stuart Reges from "We're flooding people with information. We.
CSC 142 Computer Science II Zhen Jiang West Chester University
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 7: Return values, Math, and double reading: 3.2,
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Variables, Arithmetic, etc.)
Building Java Programs Chapter 3 Parameters and Objects Copyright (c) Pearson All rights reserved.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Building Java Programs Parameters and Objects. 2 Redundant recipes Recipe for baking 20 cookies: –Mix the following ingredients in a bowl: 4 cups flour.
Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
1 CSE 142 Lecture Notes Conditional Execution with if Statements; Methods that Return Values (briefly) Chapters 3 and 4 Suggested reading: ;
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
Copyright 2010 by Pearson Education Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 2: Primitive Data and Definite Loops.
CS 112 Introduction to Programming Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
CS 112 Introduction to Programming Summary of Method Definition and Invocation; printf/format Formatting Yang (Richard) Yang Computer Science Department.
Copyright 2009 by Pearson Education Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1 self-check: #1-6 exercises: #1-3 videos: Ch.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Building Java Programs Chapter 3
Lecture 3: Method Parameters
Lecture 6: While Loops and the Math Class
Building Java Programs
CSCI 161 – Introduction to Programming I William Killian
Building Java Programs
Building Java Programs
Building Java Programs
Math Methods that return values
Building Java Programs
Building Java Programs
Topic 10 return values, Math methods
Building Java Programs
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
CSc 110, Spring 2017 Lecture 5: Constants and Parameters
Topic 7 parameters "We're flooding people with information. We need to feed it through a processor. A human must turn information into intelligence or.
Building Java Programs
Redundant recipes Recipe for baking 20 cookies:
Building Java Programs
Building Java Programs
Topic 10 return values, Math methods
Lecture 3: Method Parameters
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Global Constants, Parameters, Return Values
Building Java Programs
Drawing complex figures
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

CS305j Introduction to Computing Parameters and Methods 1 Topic 8 Parameters and Methods "We're flooding people with information. We need to feed it through a processor. A human must turn information into intelligence or knowledge. We've tended to forget that no computer will ever ask a new question." — Rear Admiral Grace Murray Hopper " Based on slides for Building Java Programs by Reges/Stepp, found at

CS305j Introduction to Computing Parameters and Methods 2 Reminder: global constants  In the last topic, we used global constants to fix "magic number" redundancy problems: public static final int SIZE = 3; public static void main(String[] args) { drawDiamond(); System.out.println(); drawX(); } public static void drawDiamond(){ drawCone(); drawV(); } public static void drawX(){ drawV(); drawCone(); }

CS305j Introduction to Computing Parameters and Methods 3 drawCone() method public static void drawCone(){ //draws a cone with SIZE lines for(int lineNum = 1; lineNum <= SIZE; lineNum++){ //spaces before the forward slash for(int j = 1; j <= SIZE - lineNum; j++) System.out.print(" "); System.out.print("/"); //spaces between the forward slash and back slash for(int j = 1; j <= (lineNum - 1) * 2; j++) System.out.print(" "); System.out.println("\\"); }

CS305j Introduction to Computing Parameters and Methods 4 drawV() method public static void drawV(){ //draws a V with SIZE lines for(int lineNum = 1; lineNum <= SIZE; lineNum++){ // print spaces before back slash for(int j = 1; j <= lineNum - 1; j++) System.out.print(" "); System.out.print("\\"); // print spaces between back slash and forward slash for(int j = 1; j <= (SIZE - lineNum) * 2; j++) System.out.print(" "); System.out.println("/"); }

CS305j Introduction to Computing Parameters and Methods 5 Another repetitive figure  Now consider the task of drawing the following figures: ************* ******* ********** * ********** ***** * *****  We'd like to structure the input using static methods, but each figure is different. –What can we do?  Note on drawing figures: It is the ability to generalize and break the problem into smaller steps that is important!

CS305j Introduction to Computing Parameters and Methods 6 A poor solution  Using what we already know, we could write a solution with the following methods: –A method to draw a line of 13 stars. –A method to draw a line of 7 stars. –A method to draw a box of stars, size 10 x 3. –A method to draw a box of stars, size 5 x 4.  These methods would be largely redundant.  Constants would not help us solve this problem, because we do not want to share one value but want to run similar code with many values.

CS305j Introduction to Computing Parameters and Methods 7 A poor solution public static void oneLine13stars() public static void oneLine7stars() public static void draw10By3Box() public static void draw5By4Box() public static void draw12By100Box()

CS305j Introduction to Computing Parameters and Methods 8 A better solution  A better solution would look something like this: –A method to draw a line of any number of stars. –A method to draw a box of stars of any size.  It is possible to write parameterized methods; methods that are passed information when they are called which affects their behavior. –Example: A parameterized method to draw a line of stars might ask us to specify how many stars to draw.  parameter: A value given to a method by its caller, which takes the form of a variable inside the method's code. The method can use the value of this variable to adjust its behavior.

CS305j Introduction to Computing Parameters and Methods 9 Methods with parameters  Declaring a method that accepts a parameter: public static void ( ){ ; } –Example: // Prints the given number of spaces. public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } Does the declaration look like any other kind of statement we have already learned?

CS305j Introduction to Computing Parameters and Methods 10 Passing parameters  Calling a method and specifying a value for its parameter is called passing a parameter.  Method call with passing parameter syntax: ( ); –Example: System.out.print("*"); printSpaces(7); System.out.print("**"); int x = 3 * 5; printSpaces(x + 2); System.out.println("***"); –Output: * ** ***

CS305j Introduction to Computing Parameters and Methods 11 How parameters are passed  formal parameter: The variable declared in the method. Sometimes just called the parameter  actual parameter: The value written between the parentheses in the call. Sometimes just called the argument –When the program executes, the actual parameter's value is stored into the formal parameter variable, then the method's code executes. printSpaces( 13 );... public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } count will take the value 13 for this method call

CS305j Introduction to Computing Parameters and Methods 12 Parameterized figure  This code parameterizes the lines of stars: public static void main(String[] args) { drawLineOfStars(13); System.out.println(); drawLineOfStars(7); } public static void drawLineOfStars(int length) { for (int i = 1; i <= length; i++) { System.out.print("*"); } System.out.println(); } Output: ************* *******

CS305j Introduction to Computing Parameters and Methods 13 Creating general solutions  The ability to parameterize problems is a way of generalizing them, and this is a VERY important skill in programming!

CS305j Introduction to Computing Parameters and Methods 14 Parameter details  If a method accepts a parameter, it is illegal to call it without passing any value for that parameter. –printSpaces(); // SYNTAX ERROR  The actual parameter value passed to a method must be of the correct type, matching the type of the formal parameter variable. –printSpaces(3.7); // SYNTAX ERROR must int  Two methods may have the same name as long as they accept different parameters (this is called overloading). public static void printLineOfStars() {... } public static void printLineOfStars(int length) {... }

CS305j Introduction to Computing Parameters and Methods 15 Value parameter behavior  value parameter: When primitive variables (such as int or double) are passed as parameters in Java, their values are copied and stored into the method's formal parameter. –Modifying the formal parameter variable's value will not affect the value of the variable which was passed as the actual parameter. int x = 23; strange(x); System.out.println(x); // this x is unaffected... public static void strange(int x) { x = x + 1; // modifies the x in strange System.out.println(x); } Draw the boxes to understand the behavior! Output: 24 23

CS305j Introduction to Computing Parameters and Methods 16 Multiple parameters  A method can accept more than one parameter, separated by commas: public static void (,,..., ) { ; } –Example: public static void printPluses(int lines, int count) { for (int line = 1; line <= lines; line++) { for (int i = 1; i <= count; i++) { System.out.print("+"); } System.out.println(); }

CS305j Introduction to Computing Parameters and Methods 17 Parameterized box figure  This code parameterizes the boxes of stars: public static void main(String[] args) { drawBoxOfStars(10, 3); System.out.println(); drawBoxOfStars(4, 5); } public static void drawBoxOfStars(int width, int height) drawLineOfStars(width); for (int line = 1; line <= height - 2; line++) { System.out.print("*"); printSpaces(width - 2); System.out.println("*"); } drawLineOfStars(width) }

CS305j Introduction to Computing Parameters and Methods 18 Java's Math class  Java has a class called Math that has several useful methods that perform mathematical calculations. –The Math methods are called by writing: Math. ( ); Method nameDescription abs(value)absolute value cos(value)cosine, in radians log(value)logarithm base e max(value1, value2)larger of two values min(value1, value2)smaller of two values pow(value1, value2)value1 to the value2 power random() random double between 0 and 1 round(value)returns nearest whole number sin(value)sine, in radians sqrt(value)square root

CS305j Introduction to Computing Parameters and Methods 19 Methods that "return" values  The methods of the Math class do not print their results to the console. –Instead, a call to one of these methods can be used as an expression or part of an expression. –The method evaluates to produce (or return) a numeric result. –The result can be printed or used in a larger expression. –Example: double squareRoot = Math.sqrt(121.0); System.out.println(squareRoot); // 11.0 int absoluteValue = Math.abs(-50); System.out.println(absoluteValue); // 50 System.out.println(Math.min(3, 7) + 2); // 5

CS305j Introduction to Computing Parameters and Methods 20 Methods that return values  Declaring a method that returns a value: public static ( ) { ; }  Returning a value from a method: return ;  Example: // Returns the given number cubed (to the third power). public static int cube(int number) { return number * number * number; }

CS305j Introduction to Computing Parameters and Methods 21 Example returning methods // Converts Fahrenheit to Celsius. public static double fToC(double degreesF) { return 5.0 / 9.0 * (degreesF - 32); } // Rounds the given real number to the nearest whole number. // Examples: round(3.1415) returns 3 and round(4.75) returns 5. public static int round(double value) { return (int) (value + 0.5); }  Write a method to calculate the number of seconds in a given number of years.  Write a method to determine the Nth digit of a given integer.  Write a method to calculate the distance between two points.  Write a method to calculate N factorial (N!).  Write a method to calculate the slope of a line.

CS305j Introduction to Computing Parameters and Methods 22 How to comment: methods  If your method accepts parameters and/or returns a value, write a brief description of what the parameters are used for and what kind of value will be returned. –In your comments, you can also write your assumptions about the values of the parameters. –You may wish to give examples of what values your method returns for various input parameter values. –Example: // This method returns the factorial of the given integer n. // The factorial is the product of all integers up to that number. // I assume that the parameter value is non-negative. // Example: factorial(5) returns 1 * 2 * 3 * 4 * 5 = 120. public static int factorial(int n) { //implementation of factorial }