Chapter 06
Chapter 06
Chapter 6
Methods
Methods
An area box
Such a “box” is a metaphor for a method. A
method is very much like a mathematical
function – a black box that computes an
output given some inputs.
Java's Pre-defined Methods
• The values that you supply or pass to the method are called
arguments. The value computed by the method is the
returned value.
Example:
Determine the distance (in feet) from sea level to your eyes.
Compute the square root of that distance.
Multiply the result by 1.23.
Problem statement:
is that variable root is assigned the value 5.0, the square root of
25.0.
•This method, which calculates square root, is a member of Java's
Math class.
•The name of the method is sqrt, and the argument that is supplied
to the method is the number 25.0.
Math.sqrt(double x)
In the statement
the Math.sqrt(…) method is called (or invoked) with the argument 25.0 and
returns the value 5.0 (the square root of 25.0) which is subsequently
assigned to the variable root.
double x = input.nextDouble();
double y = input.nextDouble();
return-type name(parameter-list)
returns xy.
The
double Math.random()
0.6516831128923004
0.3159760705754926
0.945877632966408
0.04538322890407964
0.8815999823052094
0.07672479266883347
0.04423548066038108
0.4441137107417066
0.15348060768674676
0.1833850393131755
Using Math.random() to Generate Integers
To simulate the roll of a single die, a program requires a random integer from 1 to 6
inclusive. Use Math.random() to
generate integers in the range 1 through 6 by “magnifying” its 0 through 1 range.
Suppose
r = Math.random();
Then
.
Using Math.random() to Generate Integers
For example, if :
r = 0.8929343993861253, then
6*r = 5.3576063963167518, and
6*r+1 = 6.3576063963167518.
(int)(6*Math.random() + 1)
Problem statement
Write a program that rolls a pair of dice 100 times and counts
the number of times seven appears..
Using Math.random() to Generate Integers
1. import java.util.*;
2. public class Dice
3. {
4. public static void main(String [] args)
5. {
6. int die1,die2;
7. int sum, seven = 0;
8. for (int i = 1; I <= 100; i++)
9. {
10. die1 = (int)(6*Math.random()+1) ; // random integer 1..6
11. die2 = (int)(6*Math.random()+ 1);
12. sum = die1 + die2;
13. if (sum == 7)
14. seven = seven + 1;
15. }
16. System.out.println("The number of sevens is " + seven);
17. }
18. }
Writing Your Own Methods
• Has a name
that accepts two arguments of type double, and returns a value of type
double.
1. import java.util.*;
2. public class RunnersCalculator
3. {
4.
5. public static double caloriesBurned(double weight, double
distance)
6. {
caloriesBurned(155.5, 3.5)
the parameter weight gets the value 155.5, and distance the
value 3.5.
Methods that Return a Value
return expression
.
The return statement
Line 24:
totalCalories =
caloriesBurned(myWeight,myDistance);
5* Math.sqrt(25)
5*drawSquare(25)
System.out.println(“Print me!”);
or
drawSquare(10);
Void Methods
Problem statement:
1. import java.util.*;
2. public class MoneyChanger
3. {
4. public static void coinChanger (int amount)
5. {
6. // calculates the minimum number of half dollars, quarters, dimes,
// nickels and pennies in amount
7. int halfDollars, quarters, dimes, nickels, pennies;
8. System.out.println();
9. System.out.println(amount+" cents can be converted to:");
coinChanger (money);
The parameters in the header specify the number and type of the arguments that must be
passed to the method. When a method is invoked, the values stored in the arguments are
copied to the parameters.
Putting It All Together
The method block is a sequence of statements enclosed by
curly braces:
{
statement-1;
statement-2;
statement-3;
…
statement-n;
}
A method that calculates the volume of a
box
Putting It All Together
• Method Name
• Parameter-List.
A method's parameter-list consists of pairs of the form:
type parameter-name
Putting It All Together
• Argument Passing.
• Pass by Value.
All arguments are passed “by value.” This means that the
arguments are evaluated and values of the arguments are
copied to the parameters of a method. Subsequently,
modifying the parameters in the method has no effect on the
value of any variables passed as arguments.
Putting It All Together
• Method Block.
return expression
• Local Variables.
• The scope of a variable is that section of the program in which a variable can be
accessed or referenced.
• For example, consider the following void method that computes the sum and
product of the first n positive integers:
1. void sumAndProduct(int n)
2. {
3. int sum = 0;
4. int product = 1;
5. for (int i= 1; i<= n; i++)
6. {
7. sum += i;
8. product *= i;
9. }
10. System.out.println( "Sum of the first " + n+ " positive integers is "+ sum);
11. System.out.println("Product of the first " + n+ " positive integers is "+
product);
12. }
Scope
• The variable i does not exist beyond the block of the for-loop.
Thus, the scope of variable i is lines 5 through 9. Outside of the
for-loop, i is inaccessible and unknown.
Scope
• In general, the scope of a variable begins with its declaration
and extends to the end of the block in which it is declared.
Scope
boolean isPrime(int p)
Write a method:
Problem statement