We now consider how to write your own methods with multiple parameters. Figure D.2 uses a method called maximum
to determine and return the largest of three double
values. In main
, lines 14–18 prompt the user to enter three double
values, then read them from the user. Line 21 calls method maximum
(declared in lines 28–41) to determine the largest of the three values it receives as arguments. When method maximum
returns the result to line 21, the program assigns maximum
’s return value to local variable result
. Then line 24 outputs the maximum value. At the end of this section, we’ll discuss the use of operator + in line 24.
1 // Fig. D.2: MaximumFinder.java
2 // Programmer-declared method maximum with three double parameters.
3 import java.util.Scanner;
4
5 public class MaximumFinder
6 {
7 // obtain three floating-point values and locate the maximum value
8 public static void main( String[] args )
9 {
10 // create Scanner for input from command window
11 Scanner input = new Scanner( System.in );
12
13 // prompt for and input three floating-point values
14 System.out.print(
15 "Enter three floating-point values separated by spaces: " );
16 double number1 = input.nextDouble(); // read first double
17 double number2 = input.nextDouble(); // read second double
18 double number3 = input.nextDouble(); // read third double
19
20 // determine the maximum value
21 double result = maximum( number1, number2, number3 );
22
23 // display maximum value
24 System.out.println( "Maximum is: " + result );
25 } // end main
26
27 // returns the maximum of its three double parameters
28 public static double maximum( double x, double y, double z )
29 {
30 double maximumValue = x; // assume x is the largest to start
31
32 // determine whether y is greater than maximumValue
33 if ( y > maximumValue )
34 maximumValue = y;
35
36 // determine whether z is greater than maximumValue
37 if ( z > maximumValue )
38 maximumValue = z;
39
40 return maximumValue;
41 } // end method maximum
42 } // end class MaximumFinder
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
Enter three floating-point values separated by spaces: 5.8 12.45 8.32
Maximum is: 12.45
Enter three floating-point values separated by spaces: 6.46 4.12 10.54
Maximum is: 10.54