Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Methods Generalization of Tasks
Method Parameters• Formal
• Actual
• Limitations
• Multiple
Method Return Values
Method Signature
Method Overloading
The Math Class
Generalization of Tasks
• Related tasks can be generalized using parameters– Draw a row of stars
– So far:
drawStars() – specific number of stars only
• Parameters: Any of a set of characteristics that distinguish different members of a family of tasks– drawStars(3); , drawStars(32);
2
Method Syntax Templatepublic static void <name> (<type> <name>) {
<stmt or variable declaration>;
<stmt or variable declaration>;
...
<stmt or variable declaration>;
}
//calling a parameterized method
<name>(<expression>);
CSC116: Intro to Java Programming © Sarah Heckman
3
Formal and Actual Parameters• Formal Parameter: A variable that appears in
the parentheses in method header that is used to generalize the method’s behavior– public static void hello(String name) {
• Actual Parameters: A specific value or expression that appears inside parentheses in a method call– Must be of same type as specified in method
header– hello("John");
4
Parameter Example// Prints several lines of stars. // Uses a parameterized method to remove redundancy. public class Stars {
public static void main(String[] args) { line(13); line(7); line(35);
} // Prints the given number of stars plus a line break. public static void line(int count) {
for (int i = 1; i <= count; i++) { System.out.print("*");
} System.out.println();
} }
Output:************* ******* ***********************************
5
Example: Areapublic class Area {
public static void main(String[] args) {squareArea(5);int value = 10;squareArea(value);
}public static void squareArea(int side) {
int area = side * side;System.out.println("Area of square with side length " + side +
": " + area);}
}
Output:Area of square with side length 5: 25Area of square with side length 10: 100
Parameter Limitations• The parameter of a method only has scope
within the method– side can only be referenced in squareArea()
– main cannot use the variable side from squareArea()
• Parameters cannot be used to change values of primitive types outside of a method– If there was a variable also named side in the main
method, any changes to side in squareArea() would ONLY affect the variable side in squareArea()
7
Example: Areapublic class Area {
public static void main(String[] args) {squareArea(5);System.out.println(side); //error!int side = 10;squareArea(side);System.out.println(side); //prints 10
}public static void squareArea(int side) {
side++;System.out.println("Area of square with side length " +
side + ": " + side * side);}
}
Multiple Parameterspublic static void <name> ( <type> <name>,
<type> <name>,
...,
<type> <name>) {
<stmt or variable declaration>;
<stmt or variable declaration>;
...
<stmt or variable declaration>;
}
//calling a method with multiple parameters
<name>(<expr>, <expr>, ..., <expr>);
CSC116: Intro to Java Programming © Sarah Heckman
9
Example: Averagepublic class Average {
public static void main(String[] args) {average(2, 4, 9);int x = 5;average(x, x-5, 22/3);
}
public static void average(int x, int y, int z) {double sum = x + y + z;double average = sum / 3;System.out.println("Average of " + x + ", " +
y + ", and " + z + " is: " + average);}
}
Output:Average of 2, 4, and 9 is: 5.0Average of 5, 0, and 7 is: 4.0
Another Examplepublic class WriteNumbers {
public static void main(String[] args) {printNumber(4, 9);printNumber(9, 4);printNumber(12, 6);
}
public static void printNumber(int number, int count) { for (int i = 1; i <= count; i++) {
System.out.print(number); } System.out.println();
}
Output: 444444444 9999121212121212
In-class Exercise• Go to the moodle page and work on the NumberWriter.java
assignment (This is Exercise 3-1 in the textbook).
• Write a class named NumberWriter. In the class, write a method
named printNumbers that accepts a number (integer) as a
parameter and prints each number from 1 up to that number,
inclusive, boxed by square brackets.
• You may assume that the value of the parameter passed to
printNumbers is 1 or greater.
• Put the method calls printNumbers(15) and printNumbers(5) in
your main method.
These calls should produce the following output :
[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15]
[1] [2] [3] [4] [5]
Method Signature
• Method Signature – The name of a method, along with its number and type of parameters.
average(int, int, int)
Method Overloading
• Method Overloading – The ability to define two or more different methods with the same name but different method signatures.
average(int, int, int)
average(int, int)
Overloading Examplepublic class Average {
public static void main(String[] args) {average(2, 4, 8);average(3, 8);
}
public static void average(int x, int y, int z) {double sum = x + y + z;double average = sum / 3;System.out.println(" Average of " + x + ", " +
y + ", and " + z + " is: " + average);}
public static void average(int x, int y) {double sum = x + y;double average = sum / 2;System.out.println("Average of " + x + "and " +
y + " is: " + average);}
}
Return Values
• Return - To send a value out as a result of a method that can be used in an expression in your program
public static double average(int x, int y, int z) {
– double is the return type
• Void methods do not return any value
public static void average(int x, int y, int z) {
16
Return Statements• Specifies the value to return, terminating the
method
return <expression>;
• Statements after the return statement will not be executed
• Methods with a non-void return type must contain one or more return statement(s).
– The compiler will let you know if you’re missing one.
CSC116: Intro to Java Programming © Sarah Heckman
17
Methods Syntax Template Updated
public static <type> <name> ( <type> <name>,
<type> <name>,
...,
<type> <name>) {
<stmt or variable declaration>;
<stmt or variable declaration>;
...
<stmt or variable declaration>;
return <expression>;
}
CSC116: Intro to Java Programming © Sarah Heckman
18
Method Return Examplepublic class Average {
public static void main(String[] args) {System.out.println(average(2, 4, 9));double result = average(3,8);System.out.println(result);
}public static double average(int x, int y, int z) {
double sum = x + y + z;double average = sum / 3;return average;
}public static double average(int x, int y) {
double sum = x + y;double average = sum / 2;return average;
}}
Output:5.05.5
Common return Errors• Many students incorrectly think that a return
statement sends a variable's name back to the calling method.
public static void main(String[] args) {
slope(0, 0, 6, 3);
System.out.println("The slope is " + result); // ERROR:
} // result not defined
public static double slope(int x1, int x2, int y1, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
double result = dy / dx;
return result;
}
Fixing the error• Instead, a return sends the variable's value back.
– The returned value must be stored into a variable or used in an expression to be useful to the caller.
public static void main(String[] args) {
double s = slope(0, 0, 6, 3);System.out.println("The slope is " + s);
}
public static double slope(int x1, int x2, int y1, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
double result = dy / dx;
return result;
}
What is the output?public class Mystery6 {
public static void main (String [] args) {
int x = 1, y = 2, z = 3;
z = mystery(x, z, y);
System.out.println(x + " " + y + " " + z);
x = mystery(z, z, x);
System.out.println(x + " " + y + " " + z);
y = mystery(y, y, z);
System.out.println(x + " " + y + " " + z);
}
public static int mystery(int z, int x, int y) {
z--;
x = 2 * y + z;
y = x - 1;
System.out.println(y + " " + z);
return x;
}
}
CSC116: Intro to Java Programming © Sarah Heckman
22
The Math Class
• Java provides many classes as part of the Java class libraries that provide implementations of many common solutions
• Java API (Application Programming Interface):– https://docs.oracle.com/javase/8/docs/api/
• Math class has predefined constants and common mathematical functions
• Since the mathematical functions/constants are in another class, we use dot notation to call the element<class name>.<element>
• See Table 3.2 on p. 155 for useful Math methods
Java's Math classMethod name Description
Math.abs(value) absolute value
Math.round(value) nearest whole number
Math.ceil(value) rounds up
Math.floor(value) rounds down
Math.log10(value) logarithm, base 10
Math.max(value1,value2)
larger of two values
Math.min(value1,value2)
smaller of two values
Math.pow(base, exp) base to the exp power
Math.sqrt(value) square root
Math.sin(value)
Math.cos(value)
Math.tan(value)
sine/cosine/tangent ofan angle in radians
Math.toDegrees(value)
Math.toRadians(value)
convert degrees toradians and back
Math.random() random double between 0 and 1
Constant Description
Math.E 2.7182818...
Math.PI 3.1415926...
Copyright 2008 by Pearson Education25
Calling Math methodsMath.methodName(parameters)
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
The Math methods do not print to the console.
Each method produces ("returns") a numeric result.
The results are used as expressions (printed, stored, etc.).
Copyright 2008 by Pearson Education26
Math 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?
Java API Documentation• Let’s practice using the Java API documentation located at:
http://docs.oracle.com/javase/8/docs/api/
• To search the API documentation:
– In the navigation panel on the left, click on the class you are researching (they are listed in alphabetical order).
– Then page down to the Method Summary section in the window on the right.
– The modifier and type column tells you if the method is a static method (modifier) and gives the data type of the value returned from the method (int, double, String, etc.).
– The method and description column gives the method signature (method name and data type of parameters) followed by a brief description of what the method does.
Java API Documentation - ExerciseFind the methods available in the classes specified below to perform the requested functions.
• Look at the method signatures and descriptions in the Double class and find the static method:
– that will convert a String input parameter (representing a decimal value) into a double and return it. Must return a double (primitive type), NOT a Double (object).
• Look at the method signatures and descriptions in the Math class and find two static methods:
– one that will return the cube root of a double input parameter
– one that will take two double parameters and return the square root of the sum of their squares.
• Look at the method signatures and descriptions in the Character class to find three static methods:
– one that will convert a char input parameter to uppercase and return it
– one that will convert a char input parameter to lowercase and return it
– one that will convert a char input parameter to a String and return it
In-class Exercise• Go to the moodle page and work on the MathCalculations.java assignment.
• Write a class named MathCalculations. Use proper javadoc to comment the class and its methods. In the class, you must write the following methods:
– A method named findMin that accepts three integers as parameters and returns the smallest of the three values. For example, the call findMin(1,10,-1) would return -1. You must use the Math class min function (which only takes 2 parameters).
– A method named findMax that accepts three doubles as parameters and returns the largest of the three values. For example, the call findMax(1,10,-1) would return 10.0. You must use the Math class max function (which only takes 2 parameters).
– A main method that:• calls findMin(5, 7, 3) and prints the returned result (see below for format).• calls findMax(-5.1, 32.5, 56.8) and prints the returned result (see below for format)• calls findMax(20, 25, 15) and prints the returned result (see below for format).
• The output of your program should be formatted as follows:The minimum of 5, 7, and 3 is 3The maximum of -5.1, 32.5, and 56.8 is 56.8The maximum of 20, 25, and 15 is 25.0
• When you are finished, use the javadoc command at your cmd prompt to create a webpage that describes your class. Note: many files will be created. Of these, you only need to submit MathCalculations.html (in addition to your MathCalculations.java file).