|
Home | Résumé | Courses | Contact | Useful Links | Favorite Links | USC - Homepage |
Computer Science 1 - (CPTR151) - Lectures
Lecture 6 - Version 1.2.1
Lecture Outline
6.1 Introduction
6.2 Program Modules in Java
6.3 Math-Class Methods
6.4 Method Declarations
6.5 Argument Promotion
6.6 Java API Packages
6.7 Random-Number Generation
6.8 Example: A Game of Chance
6.9 Methods of Class JApplet
6.10 Method Overloading
6.11 Recursion
6.12 Example Using Recursion: The Fibonacci Series
6.13 Recursion vs. Iteration
6.1 Introduction
• Modules
– Small pieces of a problem
• e.g., divide and conquer
– Facilitate design, implementation, operation and maintenance of large programs
6.2 Program Modules in Java
• Modules in Java
– Methods
– Classes
• Programmers can also create methods
– e.g., programmer-defined methods
• Methods
– Invoked by a method call
– Returns a result to calling method (caller)
– Similar to a boss (caller) asking a worker (called method) to complete a task

Hierarchical boss-method/worker-method relationship.
6.3 Math-Class Methods
• Class java.lang.Math
– Provides common mathematical calculations
– Calculate the square root of 900.0:
• Math.sqrt( 900.0 )
– Method sqrt belongs to class Math
• Dot (.) allows access to method sqrt
– The argument 900.0 is located inside parentheses

6.4 Methods Declarations
• Methods
– Allow programmers to modularize programs
• Makes program development more manageable
• Software reusability
• Avoid repeating code
– Local variables
• Declared in method declaration
– Parameters
• Communicates information between methods via method calls
• Programmers can write customized methods
•General format of method declaration:return-value-type method-name( parameter1, parameter2, …, parameterN )
{
declarations and statements
}• Method can also return values:
return expression;
1 // Fig. 6.3: SquareIntegers.java
2 // Creating and using a programmer-defined method.
3 import java.awt.Container;
4
5 import javax.swing.*;
6
7 public class SquareIntegers extends JApplet {
8
9 // set up GUI and calculate squares of integers from 1 to 10
10 public void init()
11 {
12 // JTextArea to display results
13 JTextArea outputArea = new JTextArea();
14
15 // get applet's content pane (GUI component display area)
16 Container container = getContentPane();
17
18 // attach outputArea to container
19 container.add( outputArea );
20
21 int result; // store result of call to method square
22 String output = ""; // String containing results
23
24 // loop 10 times
25 for ( int counter = 1; counter <= 10; counter++ ) {
26 result = square( counter ); // method call
27
28 // append result to String output
29 output += "The square of " + counter + " is " + result + "\n";
30
31 } // end for
32
33 outputArea.setText( output ); // place results in JTextArea
34
35 } // end method init
36
37 // square method declaration
38 public int square( int y )
39 {
40 return y * y; // return square of y
41
42 } // end method square
43
44 } // end class SquareIntegers
1 // Fig. 6.4: MaximumTest.java
2 // Finding the maximum of three floating-point numbers.
3 import java.awt.Container;
4
5 import javax.swing.*;
6
7 public class MaximumTest extends JApplet {
8
9 // initialize applet by obtaining user input and creating GUI
10 public void init()
11 {
12 // obtain user input
13 String s1 = JOptionPane.showInputDialog("Enter first floating-point value" );
14
15 String s2 = JOptionPane.showInputDialog("Enter second floating-point value" );
16
17 String s3 = JOptionPane.showInputDialog("Enter third floating-point value" );
18
19
20 // convert user input to double values
21 double number1 = Double.parseDouble( s1 );
22 double number2 = Double.parseDouble( s2 );
23 double number3 = Double.parseDouble( s3 );
24
25 double max = maximum( number1, number2, number3 ); // method call
26
27 // create JTextArea to display results
28 JTextArea outputArea = new JTextArea();
29
30 // display numbers and maximum value
31 outputArea.setText( "number1: " + number1 + "\nnumber2: " +
32 number2 + "\nnumber3: " + number3 + "\nmaximum is: " + max );
33
34 // get applet's GUI component display area
35 Container container = getContentPane();
36
37 // attach outputArea to Container c
38 container.add( outputArea );
39
40 } // end method init
41
42 // maximum method uses Math class method max to help
43 // determine maximum value
44 public double maximum( double x, double y, double z )
45 {
46 return Math.max( x, Math.max( y, z ) );
47
48 } // end method maximum
49
50 } // end class Maximum
6.5 Argument Promotion
• Coercion of arguments
– Forcing arguments to appropriate type to pass to method
• e.g., System.out.println( Math.sqrt( 4 ) );
– Evaluates Math.sqrt( 4 )
– Then evaluates System.out.println()
• Promotion rules
– Specify how to convert types without data loss

6.6 Java API Packages
• API: Application Program Interface
• Packages
– Classes grouped into categories of related classes
– Promotes software reuse
– import statements specify classes used in Java programs
• e.g., import javax.swing.JApplet;

6.7 Random-Number Generation
• Java random-number generators
– Math.random()
• ( int ) ( Math.random() * 6 )
– Produces integers from 0 – 5
– Use a seed for different random-number sequences
1 // Fig. 6.7: RandomIntegers.java
2 // Shifted, scaled random integers.
3 import javax.swing.JOptionPane;
4
5 public class RandomIntegers {
6
7 public static void main( String args[] )
8 {
9 int value;
10 String output = "";
11
12 // loop 20 times
13 for ( int counter = 1; counter <= 20; counter++ ) {
14
15 // pick random integer between 1 and 6
16 value = 1 + ( int ) ( Math.random() * 6 );
17
18 output += value + " "; // append value to output
19
20 // if counter divisible by 5, append newline to String output
21 if ( counter % 5 == 0 )
22 output += "\n";
23
24 } // end for
25
26 JOptionPane.showMessageDialog( null, output, "20 Random Numbers from 1 to 6",
27 JOptionPane.INFORMATION_MESSAGE );
28
29
30 System.exit( 0 ); // terminate application
31
32 } // end main
33
34 } // end class RandomIntegers
6.8 Example: A Game of Chance
• Craps simulation
– Roll dice first time
• If sum equals 7 or 11, the player wins
• If sum equals 2, 3 or 12, the player loses
• Any other sum (4, 5, 6, 8, 9, 10) is that player’s point
– Keep rolling dice until…
• Sum matches player point
– Player wins
• Sum equals 7
– Player loses
1 // Fig. 6.9: Craps.java
2 // Craps.
3 import java.awt.*; // Container, FlowLayout
4 import java.awt.event.*; // ActionEvent, ActionListener
5
6 import javax.swing.*; // JApplet, JButton, JLabel, JTextField
7
8 public class Craps extends JApplet implements ActionListener {
9
10 // constant variables for game status
11 final int WON = 0, LOST = 1, CONTINUE = 2;
12
13 boolean firstRoll = true; // true if first roll of dice
14 int sumOfDice = 0; // sum of the dice
15 int myPoint = 0; // point if no win or loss on first roll
16 int gameStatus = CONTINUE; // game not over yet
17
18 // graphical user interface components
19 JLabel die1Label, die2Label, sumLabel, pointLabel;
20 JTextField die1Field, die2Field, sumField, pointField;
21 JButton rollButton;
22
23 // set up GUI components
24 public void init()
25 {
26 // obtain content pane and change its layout to FlowLayout
27 Container container = getContentPane();
28 container.setLayout( new FlowLayout() );
29
30 // create label and text field for die 1
31 die1Label = new JLabel( "Die 1" );
32 container.add( die1Label );
33 die1Field = new JTextField( 10 );
34 die1Field.setEditable( false );
35 container.add( die1Field );
36
37 // create label and text field for die 2
38 die2Label = new JLabel( "Die 2" );
39 container.add( die2Label );
40 die2Field = new JTextField( 10 );
41 die2Field.setEditable( false );
42 container.add( die2Field );
43
44 // create label and text field for sum
45 sumLabel = new JLabel( "Sum is" );
46 container.add( sumLabel );
47 sumField = new JTextField( 10 );
48 sumField.setEditable( false );
49 container.add( sumField );
50
51 // create label and text field for point
52 pointLabel = new JLabel( "Point is" );
53 container.add( pointLabel );
54 pointField = new JTextField( 10 );
55 pointField.setEditable( false );
56 container.add( pointField );
57
58 // create button user clicks to roll dice
59 rollButton = new JButton( "Roll Dice" );
60 rollButton.addActionListener( this );
61 container.add( rollButton );
62
63 } // end method init
64
65 // process one roll of dice
66 public void actionPerformed( ActionEvent actionEvent )
67 {
68 sumOfDice = rollDice(); // roll dice
69
70 // first roll of dice
71 if ( firstRoll ) {
72
73 switch ( sumOfDice ) {
74
75 // win on first roll
76 case 7:
77 case 11:
78 gameStatus = WON;
79 pointField.setText( "" ); // clear point field
80 break;
81
82 // lose on first roll
83 case 2:
84 case 3:
85 case 12:
86 gameStatus = LOST;
87 pointField.setText( "" ); // clear point field
88 break;
89
90 // remember point
91 default:
92 gameStatus = CONTINUE;
93 myPoint = sumOfDice;
94 pointField.setText( Integer.toString( myPoint ) );
95 firstRoll = false;
96 break;
97
98 } // end switch
99
100 } // end if part of if...else
101
102 else { // subsequent roll of dice
103
104 // determine game status
105 if ( sumOfDice == myPoint ) // win by making point
106 gameStatus = WON;
107 else
108 if ( sumOfDice == 7 ) // lose by rolling 7
109 gameStatus = LOST;
110
111 } // end else part of if...else
112
113 displayMessage(); // display message indicating game status
114
115 } // end method actionPerformed
116
117 // roll dice, calculate sum and display results
118 public int rollDice()
119 {
120 // pick random die values
121 int die1 = 1 + ( int ) ( Math.random() * 6 );
122 int die2 = 1 + ( int ) ( Math.random() * 6 );
123
124 int sum = die1 + die2; // sum die values
125
126 // display results in textfields
127 die1Field.setText( Integer.toString( die1 ) );
128 die2Field.setText( Integer.toString( die2 ) );
129 sumField.setText( Integer.toString( sum ) );
130
131 return sum; // return sum of dice
132
133 } // end method rollDice
134
135 // determine game status; display appropriate message in status bar
136 public void displayMessage()
137 {
138 // game should continue
139 if ( gameStatus == CONTINUE )
140 showStatus( "Roll again." );
141
142 else { // game won or lost
143
144 if ( gameStatus == WON )
145 showStatus( "Player wins. Click Roll Dice to play again." );
146 else
147 showStatus( "Player loses. Click Roll Dice to play again." );
148
149 firstRoll = true; // next roll is first roll of new game
150
151 } // end else part of if...else
152
153 } // end method displayMessage
154
155 } // end class Craps
![]()
![]()
6.9 Methods of Class JApplet
• Java API (Application Programs Interfaces) defines several JApplet methods
– Defining methods of Fig. 6.11 in a JApplet is called overriding those methods.

6.10 Method Overloading
• Method overloading
– Several methods of the same name
– Different parameter set for each method
• Number of parameters
• Parameter types
1 // Fig. 6.12: MethodOverload.java
2 // Using overloaded methods
3 import java.awt.Container;
4
5 import javax.swing.*;
6
7 public class MethodOverload extends JApplet {
8
9 // create GUI and call each square method
10 public void init()
11 {
12 JTextArea outputArea = new JTextArea();
13 Container container = getContentPane();
14 container.add( outputArea );
15
16 outputArea.setText( "The square of integer 7 is " + square( 7 ) +
17 "\nThe square of double 7.5 is " + square( 7.5 ) );
18
19 } // end method init
20
21 // square method with int argument
22 public int square( int intValue )
23 {
24 System.out.println( "Called square with int argument: " + intValue );
25
26
27 return intValue * intValue;
28
29 } // end method square with int argument
30
31 // square method with double argument
32 public double square( double doubleValue )
33 {
34 System.out.println( "Called square with double argument: " + doubleValue );
35
36
37 return doubleValue * doubleValue;
38
39 } // end method square with double argument
40
41 } // end class MethodOverload
1 // Fig. 6.13: MethodOverload.java
2 // Overloaded methods with identical signatures.
3 import javax.swing.JApplet;
4
5 public class MethodOverload extends JApplet {
6
7 // declaration of method square with int argument
8 public int square( int x )
9 {
10 return x * x;
11 }
12
13 // second declaration of method square
14 // with int argument causes syntax error
15 public double square( int y )
16 {
17 return y * y;
18 }
19
20 } // end class MethodOverload
6.11 Recursion
• Recursive method
– Calls itself (directly or indirectly) through another method
– Method knows how to solve only a base case
– Method divides problem
• Base case
• Simpler problem
– Method now divides simpler problem until solvable
– Recursive call
– Recursive step
Recursive evaluation of 5!.
1 // Fig. 6.15: FactorialTest.java
2 // Recursive factorial method.
3 import java.awt.*;
4
5 import javax.swing.*;
6
7 public class FactorialTest extends JApplet {
8 JTextArea outputArea;
9
10 // create GUI and calculate factorials of 0-10
11 public void init()
12 {
13 outputArea = new JTextArea();
14
15 Container container = getContentPane();
16 container.add( outputArea );
17
18 // calculate the factorials of 0 through 10
19 for ( long counter = 0; counter <= 10; counter++ )
20 outputArea.append( counter + "! = " + factorial( counter ) + "\n" );
21
22
23 } // end method init
24
25 // recursive declaration of method factorial
26 public long factorial( long number )
27 {
28 // base case
29 if ( number <= 1 )
30 return 1;
31
32 // recursive step
33 else
34 return number * factorial( number - 1 );
35
36 } // end method factorial
37
38 } // end class FactorialTest
6.12 Example Using Recursion: The Fibonacci Series
• Fibonacci series
– Each number in the series is sum of two previous numbers
• e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21…fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n-1) + fibonacci( n – 2 )• fibonacci(0) and fibonacci(1) are base cases
– Golden ratio (golden mean)
1 // Fig. 6.16: FibonacciTest.java
2 // Recursive fibonacci method.
3 import java.awt.*;
4 import java.awt.event.*;
5
6 import javax.swing.*;
7
8 public class FibonacciTest extends JApplet implements ActionListener {
9 JLabel numberLabel, resultLabel;
10 JTextField numberField, resultField;
11
12 // set up applet’s GUI
13 public void init()
14 {
15 // obtain content pane and set its layout to FlowLayout
16 Container container = getContentPane();
17 container.setLayout( new FlowLayout() );
18
19 // create numberLabel and attach it to content pane
20 numberLabel = new JLabel( "Enter an integer and press Enter" );
21 container.add( numberLabel );
22
23 // create numberField and attach it to content pane
24 numberField = new JTextField( 10 );
25 container.add( numberField );
26
27 // register this applet as numberField’s ActionListener
28 numberField.addActionListener( this );
29
30 // create resultLabel and attach it to content pane
31 resultLabel = new JLabel( "Fibonacci value is" );
32 container.add( resultLabel );
33
34 // create numberField, make it uneditable
35 // and attach it to content pane
36 resultField = new JTextField( 15 );
37 resultField.setEditable( false );
38 container.add( resultField );
39
40 } // end method init
41
42 // obtain user input and call method fibonacci
43 public void actionPerformed( ActionEvent event )
44 {
45 long number, fibonacciValue;
46
47 // obtain user’s input and convert to long
48 number = Long.parseLong( numberField.getText() );
49
50 showStatus( "Calculating ..." );
51
52 // calculate fibonacci value for number user input
53 fibonacciValue = fibonacci( number );
54
55 // indicate processing complete and display result
56 showStatus( "Done." );
57 resultField.setText( Long.toString( fibonacciValue ) );
58
59 } // end method actionPerformed
60
61 // recursive declaration of method fibonacci
62 public long fibonacci( long n )
63 {
64 // base case
65 if ( n == 0 || n == 1 )
66 return n;
67
68 // recursive step
69 else
70 return fibonacci( n - 1 ) + fibonacci( n - 2 );
71
72 } // end method fibonacci
73
74 } // end class FibonacciTest
![]()
![]()
![]()
![]()
![]()
![]()
FibonacciTest.java
6.13 Recursion vs. Iteration
• Iteration
– Uses repetition structures (for, while or do…while)
– Repetition through explicitly use of repetition structure
– Terminates when loop-continuation condition fails
– Controls repetition by using a counter
• Recursion
– Uses selection structures (if, if…else or switch)
– Repetition through repeated method calls
– Terminates when base case is satisfied
– Controls repetition by dividing problem into simpler one
Source: Java How to Program – 5th Edition – Deitel & Deitel
|
Home | Résumé | Courses | Contact | Useful Links | Favorite Links | USC - Homepage |