1 / 36

Building Java Programs

Building Java Programs. Chapter 3: Introduction to Parameters and Objects modified by Pepper. Parameters. input parameters -  INTO a method call methods with parameters (like Math.pow and println) define methods with parameters call your own static methods

samara
Télécharger la présentation

Building Java Programs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Building Java Programs Chapter 3: Introduction to Parameters and Objects modified by Pepper

  2. Parameters • input parameters - INTO a method • call methods with parameters • (like Math.pow and println) • define methods with parameters • call your own static methods • methods that return values - OUT of a method • call methods that return values (e.g. the Math class) • define your own methods that return values • call your own static methods

  3. Stairs • 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

  4. 7 drawLine main ******* 13 drawLine ************* Parameterization • parameterized method: The calling method (main) can tell it some information (e.g. number of stars to draw, or what to print) • parameter: A value passed to a method by its caller. • Writing parameterized methods requires 2 steps: • define the method to accept the parameter • call the method and pass the parameter value(s) desired

  5. Writing parameterized methods • Define Parameterized method declaration syntax: public static void <name>(<type><name>) { <statement(s)>; } • Example: you type this public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } } • Whenever printSpaces is called, the caller must specify how many spaces to print.

  6. Calling parameterized methods • passing a parameter: Calling a parameterized method and specifying a value for its parameter(s). • Parameterized method call syntax: <name> (<expression>); • Example: System.out.print("*"); printSpaces(7); System.out.print("**"); int x = 3 * 5; printSpaces(x + 2); System.out.println("***"); Output: * ** ***

  7. 7 13 How parameters are passed • When the parameterized method call executes: • 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) { printSpaces(7); printSpaces(13); } public static void printSpaces(intcount) { for (inti = 1; i <= count; i++) { System.out.print(" "); } }

  8. New man solution using printSpaces Public static void main(){ for (int man = 5; man >= 1; man--){ printSpaces(man*6); System.out.println(“ o *”); printSpaces(man*6); System.out.println(“ /|\\ *”); • printSpaces(man*6); System.out.println(“ /\\ *”); } } public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } }

  9. Value semantics • value semantics: When primitive variables (int, double) are passed as parameters, their values are copied. • 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); // unchanged ... } public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); } Output: 1. x = 24 2. x = 23

  10. Common errors • If a method accepts a parameter, it is illegal to call it without passing any value for that parameter. printSpaces(); // ERROR: parameter value required • The value passed to a method must be of the correct type, matching the type of its parameter variable. printSpaces(3.7); // ERROR: must be of type int • Exercise:  you type this • a printSpaces method to print the given number of spaces (but no line return) • a drawLine 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.

  11. Multiple parameters • Methods can accept multiple parameters. • 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>,...,<type><name>) { <statement(s)>; } • Multiple parameters call syntax: <name> (<expression>, <expression>, ..., <expression> );

  12. Multiple parameters example public static void main(String[] args) { printNumber(4, 9); printNumber(17, 6); printNumber(8, 0); printNumber(0, 8); } public static void printNumber(int number, int count) { for (int i = 1; i <= count; i++) { System.out.print(number); } System.out.println(); } Output: 444444444 171717171717 00000000 • Exercise: Add a drawBox method to draw boxes of stars for a given height and width using the methods you already created: drawLine and printSpaces.

  13. Stars solution // Prints several lines and boxes made of stars. // Third version with multiple parameterized methods. public class Stars3 { public static void main(String[] args) { drawLine(13); drawLine(7); drawLine(35); System.out.println(); drawBox(10, 3); drawBox(5, 4); drawBox(20, 7); } // Prints the given number of stars plus a line break. public static void drawLine(int count) { for (int i = 1; i <= count; i++) { System.out.print("*"); } System.out.println(); } ...

  14. Stars solution, cont'd. ... // Prints a box of stars of the given size. public static void drawBox(int width, int height) { drawLine(width); for (int i = 1; i <= height - 2; i++) { System.out.print("*"); printSpaces(width - 2); System.out.println("*"); } drawLine(width); } // Prints the given number of spaces. public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } } }

  15. Parameter "mystery" problem • 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

  16. Parameter question • 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

  17. Parameter answer • 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++) { printSpaces(i - 1); drawLine(2 * height + 1 - 2 * i); } } ... }

  18. Parameter questions • Write a method named printDiamond that accepts a height as a parameter and prints a diamond figure: * *** ***** *** * • Write a method named multiplicationTable 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 bottlesOfBeer that accepts an integer as a parameter and prints the "XX Bottles of Beer" song with that many verses.

  19. Methods that return values reading: 3.2

  20. Java's Math class • Java has a class named Math with useful static methods and constants for performing calculations.

  21. Math.abs -42 42 main 2.71 3 Math.round Methods that return values • return: To send a value out as the result of a method, which can be used in an expression. • A return is like the opposite of a parameter: • Parameters pass information in from the caller to the method. • Return values pass information out from a method to its caller. • 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.

  22. Math method examples • Math method call syntax: Math.<method name> (<parameter(s)> ) • Examples: 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 • Notice that the preceding calls are used in expressions; they can be printed, stored into a variable, etc.

  23. Math method questions • Evaluate the following expressions: • 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. • What statement would replace negative ages with 0? • What statement would cap the maximum age to 40?

  24. Methods that return values • Syntax for methods that return a value: public static <type><name>(< parameter(s)> ) { < statement(s)> ; } • Returning a value from a method: return <expression> ; • Example: // Returns the slope of the line between the given points. public static double slope(int x1, int y1, int x2, int y2) { double dy = y2 - y1; double dx = x2 - x1; return dy / dx ; }

  25. Einstein’s Formula e = m x c2: energy = mass x speed of light2 The formula itself serves as the user story Method returns an expression for right side of formula Developing the massToEnergy()method Method’s return type is a double Parameter list includes a doubletype called mass Speed of light is declared as a constant outside method Computation is performed within return statement Example of a call to massToEnergy() double energy = massToEnergy(1.0); Alice in Action with Java 25

  26. Einstein’s Formula (continued) Alice in Action with Java 26

  27. How to comment: params • 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. // Assumes that the parameter value is non-negative. // Example: factorial(5) returns 1 * 2 * 3 * 4 * 5 = 120. public static int factorial(int n) { ... }

  28. Make your own method return • 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 addIt(int x, double y) { System.out.println(“the first number is “ + x); System.out.println(“the second number is “ + y); return x + y; }

  29. Call your own non-void method • When you call a non-void method, you can place the returned value into a variable: public static void main() { int myTotal = addIt(10,5); int newTotal = myTotal*2; int newerTotal = addIt(myTotal,5); System.out.println(newerTotal); } public static int addIt(int x, double y) { System.out.println(“the first number is “ + x); System.out.println(“the second number is “ + y); return x + y; }

  30. Return examples // Converts Fahrenheit to Celsius. public static double fToC(double degreesF) { double degreesC = 5.0 / 9.0 * (degreesF - 32); return degreesC; } // 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 round2(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; }

  31. Return examples shortened // Converts Fahrenheit to Celsius. public static double fToC(double degreesF) { return 5.0 / 9.0 * (degreesF - 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 round2(double value) { return Math.round(value * 100) / 100; }

  32. 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

  33. Non-void Method exercise Alice in Action with Java 33 Write a method called getBMI that calculates a person’s Body Mass Index. The formula is: BMI = Weight (lb) / (Height (in) x Height (in)) x 703 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 160lb, Ted has a bmi of 25.8 At 55” and 160lb, Mary has a bmi of <whatever it returns> Extra: Mary and Ted together have an average bmi of ??

  34. How to start Alice in Action with Java 34 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 getBMI (double weight, double height){ return 3.3;} Write some tests: • Right click to create test class • Right click to create a test method for 160 lbs and 66” = 25.8 • Right click to create a test method for 160 lbs and 55” = 37.2 • Right click to create a test method for 1 lbs and 1” = 703

  35. Return questions YOU TRY AGAIN: Write a method named area that accepts a circle's radius as a parameter and returns its area. • You may wish to use the constant Math.PI in your solution. • Area = PI * r squared

  36. Parameters NOW YOU KNOW HOW TO: • input parameters - INTO a method • call methods with parameters • (like Math.pow and println) • define methods with parameters • call your own static methods • methods that return values - OUT of a method • call methods that return values (e.g. the Math class) • define your own methods that return values • call your own static methods

More Related