Building Java Programs Chapter 3 Introduction to Parameters
Building Java Programs Chapter 3: Introduction to Parameters and Objects modified by Pepper Copyright 2006 by Pearson Education 1
Parameters n input parameters - INTO a method n call methods with parameters n n (like Math. pow and println) define methods with parameters call your own static methods that return values - OUT of a method n n n call methods that return values (e. g. the Math class) define your own methods that return values call your own static methods Copyright 2006 by Pearson Education 2
Stairs n Remember how you printed the main moving up the stairs with loops inside loops? for (int man = 4; man >= 0; man--){ for (int spaces = 1; spaces < man*6; spaces++){ System. out. print(“ “); } System. out. println(“ o *”); for (int spaces = 1; spaces < man*6; spaces++){ System. out. print(“ “); } System. out. println(“ /|\ *”); for (int spaces = 1; spaces < man*6; spaces++){ System. out. print(“ “); } System. out. println(“ /\ *”); } It would be great to have one man method that could know how to print a given number of spaces Copyright 2006 by Pearson Education 3
Parameterization n parameterized method: The calling method (main) can tell it some information (e. g. number of stars to draw, or what to print) n parameter: A value passed to a method by its caller. n Writing parameterized methods requires 2 steps: n n define the method to accept the parameter call the method and pass the parameter value(s) desired main 7 13 Copyright 2006 by Pearson Education draw. Line ************* 4
Writing parameterized methods n Define Parameterized method declaration syntax: public static void <name> ( <type> <name> ) { <statement(s)> ; } n Example: you type this public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } n Whenever print. Spaces is called, the caller must specify how many spaces to print. Copyright 2006 by Pearson Education 5
Calling parameterized methods n n passing a parameter: Calling a parameterized method and specifying a value for its parameter(s). Parameterized method call syntax: <name> ( <expression> ); n Example: System. out. print("*"); print. Spaces(7); System. out. print("**"); int x = 3 * 5; print. Spaces(x + 2); System. out. println("***"); Output: * ** Copyright 2006 by Pearson Education *** 6
How parameters are passed n When the parameterized method call executes: n n n the value written is copied into the parameter variable the method's code executes using that value you type this public static void main(String[] args) { print. Spaces(7); print. Spaces(13); 13 7 } public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } Copyright 2006 by Pearson Education 7
New man solution using print. Spaces n Public static void main(){ for (int man = 5; man >= 1; man--){ print. Spaces(man*6); System. out. println(“ o *”); print. Spaces(man*6); System. out. println(“ /|\ *”); print. Spaces(man*6); System. out. println(“ /\ *”); } } public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } Copyright 2006 by Pearson Education 8
Value semantics n value semantics: When primitive variables (int, double) are passed as parameters, their values are copied. n Modifying the parameter inside the method will not affect the variable passed in. public static void main(String[] args) { int x = 23; strange(x); System. out. println("2. x = " + x); . . . } public static void strange(int x) { x = x + 1; System. out. println("1. x = " + x); } Copyright 2006 by Pearson Education // unchanged Output: 1. x = 24 2. x = 23 9
Common errors n If a method accepts a parameter, it is illegal to call it without passing any value for that parameter. print. Spaces(); n The value passed to a method must be of the correct type, matching the type of its parameter variable. print. Spaces(3. 7); n // ERROR: parameter value required // ERROR: must be of type int Exercise: you type this n n n a print. Spaces method to print the given number of spaces (but no line return) a draw. Line method to print the given number of stars (with a line return) a main method which calls both a few times to print any shape. Copyright 2006 by Pearson Education 10
Multiple parameters n Methods can accept multiple parameters. n n n The parameters are separated by commas. When the method is called, it must be passed values for each of its parameters. Multiple parameters declaration syntax: public static void <name> ( <type> <name> , . . . , <type> <name> ) { <statement(s)> ; } n Multiple parameters call syntax: <name> ( <expression>, . . . , <expression> ); Copyright 2006 by Pearson Education 11
Multiple parameters example public static void main(String[] args) { print. Number(4, 9); print. Number(17, 6); print. Number(8, 0); print. Number(0, 8); } public static void print. Number(int number, int count) { for (int i = 1; i <= count; i++) { System. out. print(number); } System. out. println(); } Output: 44444 171717 0000 n Exercise: Add a draw. Box method to draw boxes of stars for a given height and width using the methods you already created: draw. Line and print. Spaces. Copyright 2006 by Pearson Education 12
Stars solution // Prints several lines and boxes made of stars. // Third version with multiple parameterized methods. public class Stars 3 { public static void main(String[] args) { draw. Line(13); draw. Line(7); draw. Line(35); System. out. println(); draw. Box(10, 3); draw. Box(5, 4); draw. Box(20, 7); } // Prints the given number of stars plus a line break. public static void draw. Line(int count) { for (int i = 1; i <= count; i++) { System. out. print("*"); } System. out. println(); }. . . Copyright 2006 by Pearson Education 13
Stars solution, cont'd. . // Prints a box of stars of the given size. public static void draw. Box(int width, int height) { draw. Line(width); for (int i = 1; i <= height - 2; i++) { System. out. print("*"); print. Spaces(width - 2); System. out. println("*"); } } } draw. Line(width); // Prints the given number of spaces. public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } Copyright 2006 by Pearson Education 14
Parameter "mystery" problem n What is the output of the following program? public class Mystery { public static void main(String[] args) { int x = 5, y = 9, z = 2; mystery(z, y, x); System. out. println(x + " " + y + " " + z); mystery(y, x, z); System. out. println(x + " " + y + " " + z); } public static void mystery(int x, int z, int y) { x++; y = x - z * 2; x = z + 1; System. out. println(x + " " + y + " " + z); } } If time: For you to try – write your own mystery program with 1 double and 1 int – change them all in your mystery program Copyright 2006 by Pearson Education 15
Parameter question n Rewrite the following program to use parameterized methods: // Draws triangular figures of stars. public class Loops { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i - 1; j++) { System. out. print(" "); } for (int j = 1; j <= 10 - 2 * i + 1; j++) { System. out. print("*"); } System. out. println(); } for (int i = 1; i <= 12; i++) { for (int j = 1; j <= i - 1; j++) { System. out. print(" "); } for (int j = 1; j <= 25 - 2 * i; j++) { System. out. print("*"); } System. out. println(); } } } steps – make a print triangle method that accepts the length of the sides Copyright 2006 by Pearson Education 16
Parameter answer n Rewrite the following program to use parameterized methods: // Draws triangular figures using parameterized methods. public class Loops { public static void main(String[] args) { triangle(5); triangle(12); } // Draws a triangle figure of the given size. public static void triangle(int height) { for (int i = 1; i <= height; i++) { print. Spaces(i - 1); draw. Line(2 * height + 1 - 2 * i); } } } . . . Copyright 2006 by Pearson Education 17
Parameter questions n Write a method named print. Diamond that accepts a height as a parameter and prints a diamond figure: * ***** * n n Write a method named multiplication. Table that accepts a maximum integer as a parameter and prints a table of multiplication from 1 x 1 up to that integer times itself. Write a method named bottles. Of. Beer that accepts an integer as a parameter and prints the "XX Bottles of Beer" song with that many verses. Copyright 2006 by Pearson Education 18
Methods that return values reading: 3. 2 Copyright 2006 by Pearson Education 19
Java's Math class n Java has a class named Math with useful static methods and constants for performing calculations. Method name Description Constant Description abs(value) absolute value E 2. 7182818. . . ceil(value) rounds up PI 3. 1415926. . . cos(value) cosine, in radians floor(value) rounds down log(value) logarithm, base e log 10(value) logarithm, base 10 max(value 1, value 2) larger of two values min(value 1, value 2) smaller of two values pow(base, exponent) base to the exponent power random() random double between 0 and 1 round(value) nearest whole number sin(value) sine, in radians sqrt(value) square root Copyright 2006 by Pearson Education 20
Methods that return values n return: To send a value out as the result of a method, which can be used in an expression. n A return is like the opposite of a parameter: n n Parameters pass information in from the caller to the method. Return values pass information out from a method to its caller. Math. abs -42 42 main 2. 71 3 n Math. round The Math methods do not print results to the console. Instead, each method evaluates to produce (or return) a numeric result, which can be used in an expression. Copyright 2006 by Pearson Education 21
Math method examples n Math method call syntax: Math. <method name> ( <parameter(s)> ) n Examples: n double square. Root = Math. sqrt(121. 0); System. out. println(square. Root); // 11. 0 int absolute. Value = Math. abs(-50); System. out. println(absolute. Value); // 50 System. out. println(Math. min(3, 7) + 2); // 5 Notice that the preceding calls are used in expressions; they can be printed, stored into a variable, etc. Copyright 2006 by Pearson Education 22
Math method questions n Evaluate the following expressions: n n n n Math. abs(-1. 23) Math. pow(3, 2) Math. pow(10, -2) Math. sqrt(121. 0) - Math. sqrt(256. 0) Math. round(Math. PI) + Math. round(Math. E) Math. ceil(6. 022) + Math. floor(15. 9994) Math. abs(Math. min(-3, -5)) Math. max and Math. min can be used to bound numbers. Consider an int variable named age. n n What statement would replace negative ages with 0? What statement would cap the maximum age to 40? Copyright 2006 by Pearson Education 23
Methods that return values n Syntax for methods that return a value: public static <type> <name> ( < parameter(s)> ) { < statement(s)> ; } n Returning a value from a method: return <expression> ; n Example: // Returns the slope public static double dy = y 2 double dx = x 2 return dy / dx ; } Copyright 2006 by Pearson Education of the line between the given points. slope(int x 1, int y 1, int x 2, int y 2) { y 1; x 1; 24
Einstein’s Formula n e = m x c 2: energy = mass x speed of light 2 n n n Developing the mass. To. Energy()method n n n The formula itself serves as the user story Method returns an expression for right side of formula Method’s return type is a double Parameter list includes a double type called mass Speed of light is declared as a constant outside method Computation is performed within return statement Example of a call to mass. To. Energy() n double energy = mass. To. Energy(1. 0); Alice in Action with Java Copyright 2006 by Pearson Education 25 25
Einstein’s Formula (continued) Alice in Action with Java Copyright 2006 by Pearson Education 26 26
How to comment: params n 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. n n n 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. // Assumes that the parameter value is non-negative. // Example: factorial(5) returns 1 * 2 * 3 * 4 * 5 = 120. public static int factorial(int n) {. . . } Copyright 2006 by Pearson Education 27
Make your own method return n n Change “void” to the type being returned. Add a return statement to the end of your method and return the type you promised in the header. public static int add. It(int x, double y) { System. out. println(“the first number is “ + x); System. out. println(“the second number is “ + y); return x + y; } Copyright 2006 by Pearson Education 28
Call your own non-void method n When you call a non-void method, you can place the returned value into a variable: public static void main() { int my. Total = add. It(10, 5); int new. Total = my. Total*2; int newer. Total = add. It(my. Total, 5); System. out. println(newer. Total); } public static int add. It(int x, double y) { System. out. println(“the first number is “ + x); System. out. println(“the second number is “ + y); return x + y; } Copyright 2006 by Pearson Education 29
Return examples // Converts Fahrenheit to Celsius. public static double f. To. C(double degrees. F) { double degrees. C = 5. 0 / 9. 0 * (degrees. F - 32); return degrees. C; } // Computes length of triangle hypotenuse given its side lengths. public static double hypotenuse(int a, int b) { double c = Math. sqrt(a * a + b * b); return c; } // Rounds the given number to two decimal places. // Example: round(2. 71828183) returns 2. 72. public static double round 2(double value) { double result = value * 100; // upscale the number result = Math. round(result); // round to nearest integer result = result / 100; // downscale the number return result; } Copyright 2006 by Pearson Education 30
Return examples shortened // Converts Fahrenheit to Celsius. public static double f. To. C(double degrees. F) { return 5. 0 / 9. 0 * (degrees. F - 32); } // Computes length of triangle hypotenuse given its side lengths. public static double hypotenuse(int a, int b) { return Math. sqrt(a * a + b * b); } // Rounds the given number to two decimal places. // Example: round(2. 71828183) returns 2. 72. public static double round 2(double value) { return Math. round(value * 100) / 100; } Copyright 2006 by Pearson Education 31
Tester http: //www. bluej. org/tutorial/testing-tutorial. pdf Enable Junit tester: tools / preferences / show testing -- see recorder box on lower left Right click on your class to create a test class Right click on your test class to create a test then give the test a name then run your method giving it required inputs then type the expected result Right click to run all your tests View / test results to see the results Copyright 2006 by Pearson Education 32
Non-void Method exercise Write a method called get. BMI that calculates a person’s Body Mass Index. The formula is: BMI = Weight (lb) / (Height (in) x Height (in)) x 703 n Example : Someone who is 5'6" (5'6" = 66") and weights 160 lb has a BMI of 160 / (66 x 66) x 703 = 25. 8 In your main program, print the following 2 lines: At 66” and 160 lb, Ted has a bmi of 25. 8 At 55” and 160 lb, Mary has a bmi of <whatever it returns> Extra: Mary and Ted together have an average bmi ofin? ? Alice Action with Java 33 n Copyright 2006 by Pearson Education 33
How to start n n n What goes in to the equation your parameters What gets sent back your return type Write out some example input and resulting output What are the steps to get from one to the other your statements Write a stub of a method: public static double get. BMI (double weight, double height){ return 3. 3; } n Write some tests: n n Right click to to create Alice in Action with Java Copyright 2006 by Pearson Education test class a test method for 160 lbs and 66” = 25. 8 a test method for 160 lbs and 55” = 37. 2 a test method for 1 lbs and 1” = 703 34 34
Return questions YOU TRY AGAIN: Write a method named area that accepts a circle's radius as a parameter and returns its area. n You may wish to use the constant Math. PI in your solution. n Area = PI * r squared Copyright 2006 by Pearson Education 35
Parameters NOW YOU KNOW HOW TO: n input parameters - INTO a method n call methods with parameters n n (like Math. pow and println) define methods with parameters call your own static methods that return values - OUT of a method n n n call methods that return values (e. g. the Math class) define your own methods that return values call your own static methods Copyright 2006 by Pearson Education 36
- Slides: 36