Sie sind auf Seite 1von 70

Chapter 7 - Arrays

Outline
7.1
7.2
7.3
7.4
7.5
7.6
7.7
7.8
7.9
7.10

Introduction
Arrays
Declaring and Creating Arrays
Examples Using Arrays
References and Reference Parameters
Passing Arrays to Methods
Sorting Arrays
Searching Arrays: Linear Search and Binary Search
Multidimensional Arrays
(Optional Case Study) Thinking About Objects:
Collaboration Among Objects

2003 Prentice Hall, Inc. All rights reserved.

7.1

Introduction

Arrays
Data structures
Related data items of same type
Remain same size once created
Fixed-length entries

2003 Prentice Hall, Inc. All rights reserved.

7.2
Array
Group of variables
Have same type

Reference type

2003 Prentice Hall, Inc. All rights reserved.

Arrays

Name of array
(note that all
elements of this
array have the
same name, c)

Index (or subscript) of


the element in array c

Fig. 7.1
2003 Prentice Hall, Inc. All rights reserved.

c[ 0 ]

-45

c[ 1 ]

c[ 2 ]

c[ 3 ]

72

c[ 4 ]

1543

c[ 5 ]

-89

c[ 6 ]

c[ 7 ]

62

c[ 8 ]

-3

c[ 9 ]

c[ 10 ]

6453

c[ 11 ]

78

A 12-element array.

7.2

Arrays (cont.)

Index
Also called subscript
Position number in square brackets
Must be positive integer or integer expression
a = 5;
b = 6;
c[ a + b ] += 2;
Adds 2 to c[ 11 ]

2003 Prentice Hall, Inc. All rights reserved.

7.2

Arrays (cont.)

Examine array c
c is the array name
c.length accesses array cs length
c has 12 elements ( c[0], c[1], c[11] )
The value of c[0] is 45

2003 Prentice Hall, Inc. All rights reserved.

7.3

Declaring and Creating Arrays

Declaring and Creating arrays


Arrays are objects that occupy memory
Created dynamically with keyword new
int c[] = new int[ 12 ];
Equivalent to
int c[]; // declare array variable
c = new int[ 12 ]; // create array
We can create arrays of objects too
String b[] = new String[ 100 ];

2003 Prentice Hall, Inc. All rights reserved.

7.4

Examples Using Arrays

Declaring arrays
Creating arrays
Initializing arrays
Manipulating array elements

2003 Prentice Hall, Inc. All rights reserved.

7.4

Examples Using Arrays (Cont.)

Creating and initializing an array


Declare array
Create array
Initialize array elements

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Outline

// Fig. 7.2: InitArray.java


// Creating an array.
import javax.swing.*;

InitArray.java
Create 10 ints for array; each
Declare array
asinitialized
an
int is
to 0 by defaultLine 9
public static void main( String args[]
) of ints
array
Declare array as an
{
int array[];
// declare reference to an array
array of ints
array.length returns
array = new int[ 10 ]; // create array
length of array
Line 11

public class InitArray {

String output = "Index\tValue\n";


// append each array element's value to String output
for ( int counter = 0; counter < array.length; counter++ )
output += counter + "\t" + array[ counter ] + "\n";

JTextArea outputArea = new JTextArea();


outputArea.setText( output );
JOptionPane.showMessageDialog( null, outputArea,
"Initializing an Array of int Values",
JOptionPane.INFORMATION_MESSAGE );

System.exit( 0 );
} // end main

Create 10 ints for


array; each int is
initialized to 0 by
default
Line 16
array.length
returns length of
array

array[counter] returns int


Line 17
associated with index in array
array[counter]
returns int associated
with index in array

} // end class InitArray

2003 Prentice Hall, Inc.


All rights reserved.

Outline
InitArray.java
Each int is initialized Each int is
to 0 by default
initialized to 0 by
default

2003 Prentice Hall, Inc.


All rights reserved.

7.4

Examples Using Arrays (Cont.)

Using an array initializer


Use initializer list
Items enclosed in braces ({})
Items in list separated by commas
int n[] = { 10, 20, 30, 40, 50 };
Creates a five-element array
Index values of 0, 1, 2, 3, 4

Do not need keyword new

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

// Fig. 7.3: InitArray.java


// Initializing an array with a declaration.
import javax.swing.*;

Outline
Declare array as an
array of ints

public class InitArray {

InitArray.java

Line 11
public static void main( String args[] )
Compiler uses initializerDeclare
list
{
// array initializer specifies number of elements and to allocate array array of
// value for each element
int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
String output = "Index\tValue\n";
// append each array element's value to String output
for ( int counter = 0; counter < array.length; counter++ )
output += counter + "\t" + array[ counter ] + "\n";

array as an
ints

Line 11
Compiler uses
initializer list to
allocate array

JTextArea outputArea = new JTextArea();


outputArea.setText( output );
JOptionPane.showMessageDialog( null, outputArea,
"Initializing an Array with a Declaration",
JOptionPane.INFORMATION_MESSAGE );

System.exit( 0 );
} // end main
} // end class InitArray

2003 Prentice Hall, Inc.


All rights reserved.

Outline
InitArray.java
Each array element
corresponds to element
in initializer list

Each array element


corresponds to
element in initializer
list

2003 Prentice Hall, Inc.


All rights reserved.

7.4

Examples Using Arrays (Cont.)

Calculating the value to store in each array


element
Initialize elements of 10-element array to even integers

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

// Fig. 7.4: InitArray.java


// Initialize array with the even integers from 2 to 20.
Declare array
import javax.swing.*;

as an
array of ints

Outline
InitArray.java

public class InitArray {

Line 10
Create 10 ints for array
Declare array as an
array of ints

public static void main( String args[] )


{
final int ARRAY_LENGTH = 10;
// constant
int array[];
// reference to int array
array = new int[ ARRAY_LENGTH ];

// create array

// calculate value for each array element


for ( int counter = 0; counter < array.length; counter++ )
array[ counter ] = 2 + 2 * counter;
String output = "Index\tValue\n";

Line 12
Create 10 ints for
array
Line 16
Use array index to
assign array value

for ( int counter = 0; counter < array.length; counter++ )


output += counter + "\t" + array[ counter ] + "\n";
JTextArea outputArea = new JTextArea();
outputArea.setText( output );

Use array index to


assign array value

2003 Prentice Hall, Inc.


All rights reserved.

26
27
28
29
30
31
32
33
34

JOptionPane.showMessageDialog( null, outputArea,


"Initializing to Even Numbers from 2 to 20",
JOptionPane.INFORMATION_MESSAGE );

Outline
InitArray.java

System.exit( 0 );
} // end main
} // end class InitArray

2003 Prentice Hall, Inc.


All rights reserved.

7.4

Examples Using Arrays (Cont.)

Summing the elements of an array


Array elements can represent a series of values
We can sum these values

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Outline

// Fig. 7.5: SumArray.java


// Total the values of the elements of an array.
import javax.swing.*;
Declare
public class SumArray {

array with
initializer list

public static void main( String args[] )


{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
// add each element's value to total
for ( int counter = 0; counter < array.length; counter++ )
total += array[ counter ];

SumArray.java
Line 9
Declare array with
initializer list
Lines 13-14
Sum all array values

Sum all array values

JOptionPane.showMessageDialog( null,
"Total of array elements: " + total,
"Sum the Elements of an Array",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main
} // end class SumArray

2003 Prentice Hall, Inc.


All rights reserved.

7.4

Examples Using Arrays (Cont.)

Using histograms do display array data graphically


Histogram
Plot each numeric value as bar of asterisks (*)

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

// Fig. 7.6: Histogram.java


// Histogram printing program.
import javax.swing.*;

Outline
Declare array with
initializer list

public class Histogram {


public static void main( String args[] )
{
int array[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
String output = "Element\tValue\tHistogram";
// for each array element, output a bar in histogram
for ( int counter = 0; counter < array.length; counter++ ) {
output += "\n" + counter + "\t" + array[ counter ] + "\t";
// print bar of asterisks
for ( int stars = 0; stars < array[ counter ]; stars++ )
output += "*";
} // end outer for

Histogram.java
Line 9
Declare array with
initializer list
Line 19
For each array
element, print
associated number of
asterisks

For each array element, print


associated number of asterisks

JTextArea outputArea = new JTextArea();


outputArea.setText( output );

2003 Prentice Hall, Inc.


All rights reserved.

26
27
28
29
30
31
32
33

JOptionPane.showMessageDialog( null, outputArea,


"Histogram Printing Program", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );

Outline
Histogram.java

} // end main
} // end class Histogram

2003 Prentice Hall, Inc.


All rights reserved.

7.4

Examples Using Arrays (Cont.)

Using the elements of an array as counters


Use a series of counter variables to summarize data

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Outline

// Fig. 7.7: RollDie.java


// Roll a six-sided die 6000 times.
import javax.swing.*;
public class RollDie {
public static void main( String args[] )
{
int frequency[] = new int[ 7 ];

RollDie.java
Declare frequency
as
array of 7 ints
Line 9
Generate 6000 random
Declare frequency
integers in range 1-6
as array of 7 ints

// roll die 6000 times; use die value as frequency index


for ( int roll = 1; roll <= 6000; roll++ )
++frequency[ 1 + ( int ) ( Math.random() * 6 ) ];
String output = "Face\tFrequency";
Increment

frequency values at
index associated with random number
String output

// append frequencies to
for ( int face = 1; face < frequency.length; face++ )
output += "\n" + face + "\t" + frequency[ face ];
JTextArea outputArea = new JTextArea();
outputArea.setText( output );

Lines 12-13
Generate 6000
random integers in
range 1-6

Line 13
Increment
frequency values at
index associated with
random number

JOptionPane.showMessageDialog( null, outputArea,


"Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main
} // end class RollDie

2003 Prentice Hall, Inc.


All rights reserved.

7.4

Examples Using Arrays (Cont.)

Using arrays to analyze survey results


40 students rate the quality of food
1-10 Rating scale: 1 mean awful, 10 means excellent

Place 40 responses in array of integers


Summarize results

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

// Fig. 7.8: StudentPoll.java


// Student poll program.
import javax.swing.*;
public class StudentPoll {

Outline
Declare responses as
Declare
frequency as array of 11
array to store
40 responses
StudentPoll.jav
int and ignore the first
element
a

public static void main( String args[] )


{
int responses[] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6,
10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6,
4, 8, 6, 8, 10 };
int frequency[] = new int[ 11 ];

Lines 9-11
Declare responses
as array to store 40
responses

Line 12
Declare frequency
as array of 11 int
For each response, increment
and ignore the first
frequency values at index
element
String output = "Rating\tFrequency\n";
associated with that response
// append frequencies to String output
Lines 16-17
for ( int rating = 1; rating < frequency.length; rating++ )
For each response,
output += rating + "\t" + frequency[ rating ] + "\n";
increment
frequency values at
JTextArea outputArea = new JTextArea();
outputArea.setText( output );
index associated with
that response
// for each answer, select responses element and use that value
// as frequency index to determine element to increment
for ( int answer = 0; answer < responses.length; answer++ )
++frequency[ responses[ answer ] ];

2003 Prentice Hall, Inc.


All rights reserved.

28
29
30
31
32
33
34
35

JOptionPane.showMessageDialog( null, outputArea,


"Student Poll Program", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main

Outline
StudentPoll.jav
a

} // end class StudentPoll

2003 Prentice Hall, Inc.


All rights reserved.

7.4

Examples Using Arrays (Cont.)

Some additional points


When looping through an array
Index should never go below 0
Index should be less than total number of array elements

When invalid array reference occurs


Java generates ArrayIndexOutOfBoundsException
Chapter 15 discusses exception handling

2003 Prentice Hall, Inc. All rights reserved.

7.5

References and Reference Parameters

Two ways to pass arguments to methods


Pass-by-value
Copy of arguments value is passed to called method
In Java, every primitive is pass-by-value

Pass-by-reference

Caller gives called method direct access to callers data


Called method can manipulate this data
Improved performance over pass-by-value
In Java, every object is pass-by-reference
In Java, arrays are objects
Therefore, arrays are passed to methods by reference

2003 Prentice Hall, Inc. All rights reserved.

7.6

Passing Arrays to Methods

To pass array argument to a method


Specify array name without brackets
Array hourlyTemperatures is declared as
int hourlyTemperatures = new int[ 24 ];
The method call
modifyArray( hourlyTemperatures );
Passes array hourlyTemperatures to method
modifyArray

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

// Fig. 7.9: PassArray.java


// Passing arrays and individual array elements to methods.
import java.awt.Container;
import javax.swing.*;
public class PassArray extends JApplet {
// initialize applet
Declare 5-int array
public void init()
{
with initializer list
JTextArea outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );
int array[] = { 1, 2, 3, 4, 5 };

Outline
PassArray.java
Line 15
Declare 5-int
array with initializer
list

Line 24
Pass array by
Pass array by reference
to
reference
to method
method modifyArray
modifyArray

String output = "Effects of passing entire array by reference:\n" +


"The values of the original array are:\n";
// append original array elements to String output
for ( int counter = 0; counter < array.length; counter++ )
output += "
" + array[ counter ];
modifyArray( array );

// array passed by reference

output += "\n\nThe values of the modified array are:\n";

2003 Prentice Hall, Inc.


All rights reserved.

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

// append modified array elements to String output


for ( int counter = 0; counter < array.length; counter++ )
output += "
" + array[ counter ];
output += "\n\nEffects of passing array element by value:\n" +
"array[3] before modifyElement: " + array[ 3 ];
modifyElement( array[ 3 ] );

// attempt to modify array[ 3 ]

Pass array[3] by value to


modifyElement:
" +modifyElement
array[ 3 ];
method

output += "\narray[3] after


outputArea.setText( output );
} // end method init

Method modifyArray
manipulates the array directly

// multiply each element of an array by 2


public void modifyArray( int array2[] )
{
for ( int counter = 0; counter < array2.length; counter++ )
array2[ counter ] *= 2;
Method modifyElement
}

manipulates a primitives copy


// multiply argument by 2
public void modifyElement( int element )
{
element *= 2;
}

The original primitive is left unmodified

} // end class PassArray

Outline
PassArray.java
Line 35
Pass array[3] by
value to method
modifyElement
Lines 43-47
Method
modifyArray
manipulates the array
directly
Lines 50-53
Method
modifyElement
manipulates a
primitives copy
Lines 52
The original primitive
is left unmodified
2003 Prentice Hall, Inc.
All rights reserved.

Outline
PassArray.java

The object passed-by-reference


is modified

The primitive passed-by-value


is unmodified

2003 Prentice Hall, Inc.


All rights reserved.

7.7

Sorting Arrays

Sorting data
Attracted intense research in computer-science field
Bubble sort
Smaller values bubble their way to top of array
Larger values sink to bottom of array
Use nested loops to make several passes through array
Each pass compares successive pairs of elements
Pairs are left along if increasing order (or equal)
Pairs are swapped if decreasing order

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

Outline

// Fig. 7.10: BubbleSort.java


// Sort an array's values into ascending order.
import java.awt.*;
import javax.swing.*;

BubbleSort.java

public class BubbleSort extends JApplet {


// initialize applet
public void init()
Declare 10-int array
{
with initializer list
JTextArea outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );
int array[] = { 2, 6, 4, 8, 10, 12, 89, 68,

Line 15
Declare 10-int
array with initializer
list

Line 23
Pass array by
reference to method
45, 37 };
bubbleSort
to sort
Pass array by reference to
method
array
bubbleSort to sort array

String output = "Data items in original order\n";

// append original array values to String output


for ( int counter = 0; counter < array.length; counter++ )
output += "
" + array[ counter ];
bubbleSort( array );

// sort array

output += "\n\nData items in ascending order\n";

2003 Prentice Hall, Inc.


All rights reserved.

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

// append sorted\ array values to String output


for ( int counter = 0; counter < array.length; counter++ )
output += "
" + array[ counter ];

Outline
BubbleSort.java

outputArea.setText( output );

Line 36
Method
bubbleSort
Method bubbleSort receives
receives array
array reference as parameter
reference as parameter

} // end method init

// sort elements of array with bubble sort


public void bubbleSort( int array2[] )
{
// loop to control number of passes
for ( int pass = 1; pass < array2.length; pass++ ) {
// loop to control number of comparisons
for ( int element = 0;
element < array2.length - 1;
element++ ) {

Lines 39-53
Use loop and nested
Use loop and nested loop to make
loop to make passes
passes through array through array

// compare side-by-side elements and swap them if


// first element is greater than second element
if ( array2[ element ] > array2[ element + 1 ] )
swap( array2, element, element + 1 );
} // end loop to control comparisons
} // end loop to control passes

Lines 48-49
If pairs are in
decreasing order,
invoke method swap
to swap pairs

If pairs are in decreasing order,


invoke method swap to swap pairs

} // end method bubbleSort

2003 Prentice Hall, Inc.


All rights reserved.

56
57
58
59
60
61
62
63
64
65
66
67

Outline
// swap two elements of an array
public void swap( int array3[], int first, int second )
{
int hold; // temporary holding area for swap
hold = array3[ first ];
array3[ first ] = array3[ second ];
array3[ second ] = hold;
}

Method swap swaps two


values in array reference

BubbleSort.java
Lines 58-65
Method swap swaps
two values in array
reference

} // end class BubbleSort

2003 Prentice Hall, Inc.


All rights reserved.

7.8

Searching Arrays: Linear Search and


Binary Search

Searching
Finding elements in large amounts of data
Determine whether array contains value matching key value

Linear searching
Binary searching

2003 Prentice Hall, Inc. All rights reserved.

7.8

Searching Arrays: Linear Search and


Binary Search (Cont.)

Linear search
Compare each array element with search key
If search key found, return element index
If search key not found, return 1 (invalid index)

Works best for small or unsorted arrays


Inefficient for larger arrays

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

Outline

// Fig. 7.11: LinearSearch.java


// Linear search of an array.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

LinearSearch.ja
va

public class LinearSearch extends JApplet implements ActionListener {


JLabel enterLabel, resultLabel;
JTextField enterField, resultField;
int array[];

Declare array of ints

Line 11
Declare array of
ints

// set up applet's GUI


public void init()
{
// get content pane and set its layout to FlowLayout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JLabel and JTextField for user input
enterLabel = new JLabel( "Enter integer search key" );
container.add( enterLabel );
enterField = new JTextField( 10 );
container.add( enterField );
// register this applet as enterField's action listener
enterField.addActionListener( this );

2003 Prentice Hall, Inc.


All rights reserved.

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

Outline

// set up JLabel and JTextField for displaying results


resultLabel = new JLabel( "Result" );
container.add( resultLabel );

LinearSearch.ja
va
Lines 39-42
Allocate 100 ints
// create array and populate with even Create
integers
0 to
198 for array and for array and
100
ints
array = new int[ 100 ];
populate array with even ints populate array with
even ints
for ( int counter = 0; counter < array.length; counter++ )
resultField = new JTextField( 20 );
resultField.setEditable( false );
container.add( resultField );

array[ counter ] = 2 * counter;


} // end method init

Loop through array

// search array for specified key value


public int linearSearch( int array2[], int key )
{
// loop through array elements
for ( int counter = 0; counter < array2.length; counter++ )

Line 50
Loop through array

Lines 53-54
If array element at
index matches search
key, return index

// if array element equals key value, return location


if ( array2[ counter ] == key )
If array element
return counter;

at index matches
search key, return index

return -1;

// key not found

} // end method linearSearch

2003 Prentice Hall, Inc.


All rights reserved.

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

Invoked when user presses Enter

// obtain user input and call method linearSearch


public void actionPerformed( ActionEvent actionEvent )
{
// input also can be obtained with enterField.getText()
String searchKey = actionEvent.getActionCommand();

Outline

LinearSearch.ja
va

Line 61
Invoked when user
presses Enter
Invoke method linearSearch, using
Line 68
array and search key as arguments
value in element " + element );
Invoke method
linearSearch,
not found" );
using array and
search key as
arguments

// pass array reference to linearSearch; normally, a reference to an


// array is passed to a method to search corresponding array object
int element = linearSearch( array, Integer.parseInt( searchKey ) );
// display search result
if ( element != -1 )
resultField.setText( "Found
else
resultField.setText( "Value
} // method actionPerformed
} // end class LinearSearch

2003 Prentice Hall, Inc.


All rights reserved.

7.8

Searching Arrays: Linear Search and


Binary Search (Cont.)

Binary search
Efficient for large, sorted arrays
Eliminates half of the elements in search through each pass
Compare middle array element to search key
If element equals key
Return array index
If element is less than key
Repeat search on first half of array
If element is greater then key
Repeat search on second half of array
Continue search until
element equals search key (success)
Search contains one element not equal to key (failure)
2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

// Fig. 7.12: BinarySearch.java


// Binary search of an array.
import java.awt.*;
import java.awt.event.*;
import java.text.*;

Outline
BinarySearch.ja
va

import javax.swing.*;
public class BinarySearch extends JApplet implements ActionListener {
JLabel enterLabel, resultLabel;
JTextField enterField, resultField;
JTextArea output;
Declare array of ints

Line 14
Declare array of
ints

int array[];
String display = "";
// set up applet's GUI
public void init()
{
// get content pane and set its layout to FlowLayout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JLabel and JTextField for user input
enterLabel = new JLabel( "Enter integer search key" );
container.add( enterLabel );
enterField = new JTextField( 10 );
container.add( enterField );

2003 Prentice Hall, Inc.


All rights reserved.

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

Outline

// register this applet as enterField's action listener


enterField.addActionListener( this );
// set up JLabel and JTextField for displaying results
resultLabel = new JLabel( "Result" );
container.add( resultLabel );

BinarySearch.ja
va

Lines 48-51
Allocate 15 ints for
array and populate
array with even
// set up JTextArea for displaying comparison data
ints
output = new JTextArea( 6, 60 );
output.setFont( new Font( "Monospaced", Font.PLAIN,
) );for array and
Allocate 1512
ints
container.add( output );
populate array with even intsLine 56
Invoked when user
// create array and fill with even integers 0 to 28
presses Enter
array = new int[ 15 ];
resultField = new JTextField( 20 );
resultField.setEditable( false );
container.add( resultField );

for ( int counter = 0; counter < array.length; counter++ )


array[ counter ] = 2 * counter;
} // end method init

Invoked when user presses Enter


// obtain user input and call method binarySearch
public void actionPerformed( ActionEvent actionEvent )
{
// input also can be obtained with enterField.getText()
String searchKey = actionEvent.getActionCommand();

2003 Prentice Hall, Inc.


All rights reserved.

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

// initialize display string for new search


display = "Portions of array searched\n";

Outline

// perform binary search


int element = binarySearch( array, Integer.parseInt( searchKey ) );
output.setText( display );
// display search result
if ( element != -1 )
resultField.setText( "Found
else
resultField.setText( "Value

BinarySearch.ja
va
Invoke method binarySearch,
using
Line
65
array and search key as arguments
Invoke method
binarySearch,
using array and
value in element " + element );
search key as
arguments
not found" );

} // end method actionPerformed


// method to perform binary search of an array
public int binarySearch( int array2[], int key )
{
int low = 0;
// low element index
int high = array2.length - 1; // high element index
int middle;
// middle element index
// loop until low index is greater than high index
while ( low <= high ) {
middle = ( low + high ) / 2; // determine middle index
// display subset of array elements used in this
// iteration of binary search loop
buildOutput( array2, low, middle, high );

2003 Prentice Hall, Inc.


All rights reserved.

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116

Outline

// if key matches middle element, return middle location


If search key matches middle array
if ( key == array[ middle ] )
return middle;
element, return element index BinarySearch.ja

va
Lines 93-94
If search key matches
middle array
middle
element,
on second
half array
If searchrepeat
key issearch
less than
middlearray
array
// key greater than middle element, set new low element
element, return
element, repeat search on first array half
else
element index
low = middle + 1;
Lines 97-98
If search key is less
} // end while
than middle array
return -1;
// key not found
element, repeat search
on first array half
Method buildOutput displays
} // end method binarySearch
Lines 101-102
array contents being searched
// build row of output showing subset of array elements
If search key is greater
// currently being processed
than middle array
void buildOutput( int array3[], int low, int middle, int high )
element, repeat search
{
on second array half
// create 2-digit integer number format
Lines 112-137
DecimalFormat twoDigits = new DecimalFormat( "00" );
Method buildOutput displays
array contents being
searched
// if key less than middle element, set new high element
else if ( key < array[ middle ] )
high = middle - 1;
If search key is greater than

2003 Prentice Hall, Inc.


All rights reserved.

117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

Outline

// loop through array elements


for ( int counter = 0; counter < array3.length; counter++ ) {
// if counter outside current array subset, append
// padding spaces to String display
if ( counter < low || counter > high )
display += "
";

BinarySearch.ja
va

// if middle element, append element to String display


// followed by asterisk (*) to indicate middle element
else if ( counter == middle )
display += twoDigits.format( array3[ counter ] ) + "* ";
else // append element to String display
display += twoDigits.format( array3[ counter ] ) + "

Line 128
Display an asterisk
next to middle
element

";

} // end for

display += "\n";

Display an asterisk next to middle element

} // end method buildOutput


} // end class BinarySearch

2003 Prentice Hall, Inc.


All rights reserved.

Outline
BinarySearch.ja
va

2003 Prentice Hall, Inc.


All rights reserved.

7.9

Multidimensional Arrays

Multidimensional arrays
Tables with rows and columns
Two-dimensional array
Declaring two-dimensional array b[2][2]
int b[][] = { { 1, 2 }, { 3, 4 } };
1 and 2 initialize b[0][0] and b[0][1]
3 and 4 initialize b[1][0] and b[1][1]
int b[][] = { { 1, 2 }, { 3, 4, 5 } };
row 0 contains elements 1 and 2
row 1 contains elements 3, 4 and 5

2003 Prentice Hall, Inc. All rights reserved.

7.9

Multidimensional Arrays (Cont.)

Creating multidimensional arrays


Can be allocated dynamically
3-by-4 array
int b[][];
b = new int[ 3 ][ 4 ];
Rows can have different number of columns
int b[][];
b = new int[ 2 ][ ];
// allocate rows
b[ 0 ] = new int[ 5 ]; // allocate row 0
b[ 1 ] = new int[ 3 ]; // allocate row 1

2003 Prentice Hall, Inc. All rights reserved.

Row 0

Row 1

Row 2

Column 0

Column 1

Column 2

Column 3

a[ 0 ][ 0 ]

a[ 0 ][ 1 ]

a[ 0 ][ 2 ]

a[ 0 ][ 3 ]

a[ 1 ][ 0 ]

a[ 1 ][ 1 ]

a[ 1 ][ 2 ]

a[ 1 ][ 3 ]

a[ 2 ][ 0 ]

a[ 2 ][ 1 ]

a[ 2 ][ 2 ]

a[ 2 ][ 3 ]

Column index
Row index

Array name

Fig. 7.13 Two-dimensional array with three rows and four columns.

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

Outline

// Fig. 7.14: InitArray.java


// Initializing two-dimensional arrays.
import java.awt.Container;
import javax.swing.*;
public class InitArray extends JApplet {
JTextArea outputArea;
// set up GUI and initialize applet
public void init()
{
outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );

InitArray.java
Declare array1 with six Line 16
initializers in two sublists Declare array1 with
six initializers in two
sublists
Declare array2 with six
initializers in three sublists
Line 17
Declare array2 with
six initializers in three
sublists

int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } };
outputArea.setText( "Values in array1 by row are\n" );
buildOutput( array1 );
outputArea.append( "\nValues in array2 by row are\n" );
buildOutput( array2 );
} // end method init

2003 Prentice Hall, Inc.


All rights reserved.

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

Outline

// append rows and columns of an array to outputArea


public void buildOutput( int array[][] )
{
array[row].length returns number
// loop through array's rows
of columns associated with row InitArray.java
subscript
for ( int row = 0; row < array.length; row++ ) {
// loop through columns of current row
for ( int column = 0; column < array[ row ].length; column++ )
outputArea.append( array[ row ][ column ] + " " );
outputArea.append( "\n" );
}
} // end method buildOutput
} // end class InitArray

Use double-bracket notation to access


two-dimensional array values

Line 34
array[row].leng
th returns number of
columns associated
with row subscript
Line 35
Use double-bracket
notation to access twodimensional array
values

2003 Prentice Hall, Inc.


All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Outline

// Fig. 7.15: DoubleArray.java


// Two-dimensional array example.
import java.awt.*;
import javax.swing.*;

Declare grades as 3-by-4 array


DoubleArray.jav
a

public class DoubleArray extends JApplet {


int grades[][] = { { 77, 68, 86, 73 },
{ 96, 87, 89, 81 },
{ 70, 90, 86, 81 } };

int students, exams;


String output;
JTextArea outputArea;
// initialize fields
public void init()
{
students = grades.length;
exams = grades[ 0 ].length;

Each row represents a student; each


column represents an exam grade

Lines 7-9
Declare grades as 3by-4 array
Lines 7-9
Each row represents a
student; each column
represents an exam
grade

// number of students
// number of exams

// create JTextArea and attach to applet


outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );

2003 Prentice Hall, Inc.


All rights reserved.

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

Outline

// build output string


output = "The array is:\n";
buildString();
// call methods minimum and maximum
output += "\n\nLowest grade: " + minimum() +
"\nHighest grade: " + maximum() + "\n";
// call method average to calculate each student's average
for ( int counter = 0; counter < students; counter++ )
output += "\nAverage for student " + counter + " is " +
average( grades[ counter ] ); // pass one row of array

DoubleArray.jav
Determine
a minimum and
maximum for all student
Lines 31-32
Determine minimum
and maximum for all
student
grades

// change outputArea's display font


outputArea.setFont( new Font( "Monospaced", Font.PLAIN, 12 ) );
// place output string in outputArea
outputArea.setText( output );
} // end method init

Lines 35-37
Determine average for
each student

Determine average
for each student

// find minimum grade


public int minimum()
{
// assume first element of grades array is smallest
int lowGrade = grades[ 0 ][ 0 ];

2003 Prentice Hall, Inc.


All rights reserved.

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

// loop through rows of grades array


for ( int row = 0; row < students; row++ )

Outline

Use a nested loop to search


for lowest grade in series
// loop through columns of current row
DoubleArray.jav
for ( int column = 0; column < exams; column++ )
a
// if grade is less than lowGrade, assign it to lowGrade
if ( grades[ row ][ column ] < lowGrade )
lowGrade = grades[ row ][ column ];

return lowGrade;

// return lowest grade

} // end method minimum

Use a nested loop to search


for highest grade in series

// find maximum grade


public int maximum()
{
// assume first element of grades array is largest
int highGrade = grades[ 0 ][ 0 ];

Lines 54-61
Use a nested loop to
search for lowest
grade in series
Lines 74-81
Use a nested loop to
search for highest
grade in series

// loop through rows of grades array


for ( int row = 0; row < students; row++ )
// loop through columns of current row
for ( int column = 0; column < exams; column++ )
// if grade is greater than highGrade, assign it to highGrade
if ( grades[ row ][ column ] > highGrade )
highGrade = grades[ row ][ column ];

2003 Prentice Hall, Inc.


All rights reserved.

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

return highGrade;

Outline

// return highest grade

} // end method maximum

DoubleArray.jav
Method average takes
array of
a
student
test results as parameter
set
of grades)

// determine average grade for particular student (or


public double average( int setOfGrades[] )
{
int total = 0; // initialize total
Calculate
// sum grades for one student
for ( int count = 0; count < setOfGrades.length;
total += setOfGrades[ count ];
// return average of grades
return ( double ) total / setOfGrades.length;
} // end method average
// build output string
public void buildString()
{
output += "
";

Line 88
Method average
sum of array elements
takes array of student
test results as
count++ )
parameter
Divide by number of
elements to get average
Lines 93-94
Calculate sum of array
elements

// used to align column heads

Line 97
Divide by number of
elements to get
average

// create column heads


for ( int counter = 0; counter < exams; counter++ )
output += "[" + counter + "] ";

2003 Prentice Hall, Inc.


All rights reserved.

109
110
111
112
113
114
115
116
117
118
119
120

// create rows/columns of text representing array grades


for ( int row = 0; row < students; row++ ) {
output += "\ngrades[" + row + "]
";
for ( int column = 0; column < exams; column++ )
output += grades[ row ][ column ] + "
";

Outline
DoubleArray.jav
a

}
} // end method buildString
} // end class DoubleArray

2003 Prentice Hall, Inc.


All rights reserved.

7.10 (Optional Case Study) Thinking About


Objects: Collaboration Among Objects
Collaborations
When objects communicate to accomplish task
Accomplished by invoking operations (methods)

One object sends a message to another object


In 6.15, we extracted verb phrases from problem statement
Verb phrases exhibit behaviors of classes
The elevator resets its button
Elevator object sends resetButton message to
ElevatorButton object
Elevator collaborates with ElevatorButton

2003 Prentice Hall, Inc. All rights reserved.

Class
Elevator

Verb phrases
resets elevator button, rings elevator bell, signals its
arrival, signals its departure, opens its door, closes its door
ElevatorShaft
turns off light, turns on light, resets floor button
Person
presses floor button, presses elevator button, rides
elevator, enters elevator, exits elevator
FloorButton
summons (requests) elevator
ElevatorButton signals elevator to move to opposite floor
FloorDoor
signals person to enter elevator (by opening)
ElevatorDoor
signals person to exit elevator (by opening), opens floor
door, closes floor door
Fig. 7.16
Verb phrases for each class exhibiting behaviors in
simulation.

2003 Prentice Hall, Inc. All rights reserved.

An object of class...
Elevator

Sends the message... To an object of class...


resetButton
ElevatorButton
ringBell
Bell
elevatorArrived ElevatorShaft
elevatorDeparted ElevatorShaft
openDoor
ElevatorDoor
closeDoor
ElevatorDoor
ElevatorShaft
resetButton
FloorButton
turnOnLight
Light
turnOffLight
Light
Person
pressButton
FloorButton, ElevatorButton
enterElevator
Elevator
exitElevator
Elevator
FloorButton
requestElevator Elevator
ElevatorButton
moveElevator
Elevator
FloorDoor
doorOpened
Person
doorClosed
Person
ElevatorDoor
doorOpened
Person
doorClosed
Person
openDoor
FloorDoor
closeDoor
FloorDoor
Fig. 7.17 Collaborations in the elevator system.

2003 Prentice Hall, Inc. All rights reserved.

7.10 Thinking About Objects (cont.)


Collaboration diagram (UML)
Type of interaction diagram
The other is sequence diagram, discussed in Chapter 16

Models collaborations in system

2003 Prentice Hall, Inc. All rights reserved.

7.10 Thinking About Objects (cont.)


Collaboration-diagram notation
Objects are written in form objectName : ClassName
Disregard objectName only when concerned about class

Solid lines connect collaborating objects


Arrows represent messages
Indicates direction of collaboration
Points toward object receiving message
Can be implemented as a methods (synchronous calls) in Java

Message names appear next to arrows

2003 Prentice Hall, Inc. All rights reserved.

pressButton( )

: Person

: FloorButton

Fig. 7.18 Collaboration diagram of a person pressing a floor button.

2003 Prentice Hall, Inc. All rights reserved.

7.10 Thinking About Objects (cont.)


Collaboration-diagram sequence of messages
Shows in what order objects send messages
For diagrams modeling several collaborations
Progresses in numerical order
Least to greatest
Numbering starts with message 1
Follows a nested structure
Message 1.1 is first message nested in message 1
Message 3.2 is the second message nested in message 3
Message can be passed only when all nested messages
from previous message have been passed

2003 Prentice Hall, Inc. All rights reserved.

3.1 : openDoor( )

3.1.1 doorOpened( )

: FloorDoor
4.1 : resetButton( )

: FloorButton

4.2 : turnOnLight( )

: ElevatorShaft

: Light

4 : elevatorArrived( )

: Person

passenger : Person

: Elevator
3.2.1 : exitElevator( )

3.1.1.1 : enterElevator( )

3.2 : doorOpened( )
1: resetButton( )

: ElevatorButton

2: ringBell( )

3: openDoor( )

: Bell

: ElevatorDoor

Fig. 7.19 Collaboration diagram for passengers exiting and entering the elevator.
2003 Prentice Hall, Inc. All rights reserved.

7.10 Thinking About Objects (cont.)


Collaborations in Fig. 7.19
Message 1
Elevator sends resetButton to ElevatorButton

Message 2
Elevator sends ringBell to Bell

Message 3
Elevator sends openDoor to ElevatorDoor

Message 3.1
ElevatorDoor sends openDoor to FloorDoor

Message 3.1.1
FloorDoor sends doorOpened to waitingPassenger

Message 3.1.1.1
waitingPassenger sends enterElevator to
Elevator
2003 Prentice Hall, Inc. All rights reserved.

7.10 Thinking About Objects (cont.)


Collaborations in Fig. 7.20 (continued)
Message 3.2
ElevatorDoor sends doorOpened to
ridingPassenger

Message 3.2.1
Person sends exitElevator to Elevator

Message 4
Elevator sends elevatorArrived to ElevatorShaft

Message 4.1
ElevatorShaft sends resetButton to FloorButton

Message 4.2
ElevatorShaft sends turnOnLight to Light

2003 Prentice Hall, Inc. All rights reserved.

7.10 Thinking About Objects (cont.)


Unfortunately, this design has a problem
waitingPassenger enters Elevator before
ridingPassenger exits
We fix this in Section 16.11
We modify this diagram in Section 11.9 (event handling)

2003 Prentice Hall, Inc. All rights reserved.

Das könnte Ihnen auch gefallen