SlideShare a Scribd company logo
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 7 – Arrays and Array Lists
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
Chapter Goals
 To collect elements using arrays and array lists
 To use the enhanced for loop for traversing arrays and array lists
 To learn common algorithms for processing arrays and array lists
 To work with two-dimensional arrays
 To understand the concept of regression testing
Copyright © 2014 by John Wiley & Sons. All rights reserved. 3
Arrays
 An array collects a sequence of values of the same type.
 Create an array that can hold ten values of type double:
new double[10]
• The number of elements is the length of the array
• The new operator constructs the array
 The type of an array variable is the type of the element to be stored, followed by [].
Copyright © 2014 by John Wiley & Sons. All rights reserved. 4
Arrays
 To declare an array variable of type double[]
double[] values;
 To initialize the array variable with the array:
double[] values = new double[10];
 By default, each number in the array is 0
 You can specify the initial values when you create the array
double[] moreValues =
{ 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 };
Copyright © 2014 by John Wiley & Sons. All rights reserved. 5
Arrays
 To access a value in an array, specify which “slot” you want to
use
• use the [] operator
values[4] = 35;
 The “slot number” is called an index.
 Each slot contains an element.
 Individual elements are accessed by an integer index i, using
the notation array[i].
 An array element can be used like any variable.
System.out.println(values[4]);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 6
Arrays
Figure 1 An Array of Size 10
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
Syntax 7.1 Arrays
Copyright © 2014 by John Wiley & Sons. All rights reserved. 8
Arrays
 The elements of arrays are numbered starting at 0.
 The following declaration creates an array of 10 elements:
double[] values = new double[10];
 An index can be any integer ranging from 0 to 9.
 The first element is values[0]
 The last element is values[9]
 An array index must be at least zero and less than the size of
the array.
 Like a mailbox that is identified by a box number, an array
element is identified by an index.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 9
Arrays – Bounds Error
 A bounds error occurs if you supply an invalid array index.
 Causes your program to terminate with a run-time error.
 Example:
double[] values = new double[10];
values[10] = value; // Error
 values.length yields the length of the values array.
 There are no parentheses following length.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 10
Declaring Arrays
Copyright © 2014 by John Wiley & Sons. All rights reserved. 11
Array References
 An array reference specifies the location of an array.
 Copying the reference yields a second reference to the same
array.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 12
Array References
 When you copy an array variable into another, both variables refer to
the same array
int[] scores = { 10, 9, 7, 4, 5 };
int[] values = scores; // Copying array reference
 You can modify the array through either of the variables:
scores[3] = 10;
System.out.println(values[3]); // Prints 10
Figure 2 Two Array Variables Referencing the Same Array
Copyright © 2014 by John Wiley & Sons. All rights reserved. 13
Using Arrays with Methods
 Arrays can occur as method arguments and return values.
 An array as a method argument
public void addScores(int[] values)
{
for (int i = 0; i < values.length; i++)
{
totalScore = totalScore + values[i];
}
}
 To call this method
int[] scores = { 10, 9, 7, 10 };
fred.addScores(scores);
 A method with an array return value
public int[] getScores()
Copyright © 2014 by John Wiley & Sons. All rights reserved. 14
Partially Filled Arrays
 Array length = maximum number of elements in array.
 Usually, array is partially filled
 Define an array larger than you will need
final int LENGTH = 100;
double[] values = new double[LENGTH];
 Use companion variable to keep track of current size: call it
currentSize
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
Partially Filled Arrays
 A loop to fill the array
int currentSize = 0;
Scanner in = new Scanner(System.in);
while (in.hasNextDouble())
{
if (currentSize < values.length)
{
values[currentSize] = in.nextDouble();
currentSize++;
}
}
 At the end of the loop, currentSize contains the actual number
of elements in the array.
 Note: Stop accepting inputs when currentSize reaches the
array length.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 16
Partially Filled Arrays
Copyright © 2014 by John Wiley & Sons. All rights reserved. 17
Partially Filled Arrays
 To process the gathered array elements, use the companion
variable, not the array length:
for (int i = 0; i < currentSize; i++)
{
System.out.println(values[i]);
}
 With a partially filled array, you need to remember how many
elements are filled.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
Self Check 7.1
Answer:
int[] primes = { 2, 3, 5, 7, 11 };
Declare an array of integers containing the first five prime
numbers.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
Self Check 7.2
Answer: 2, 3, 5, 3, 2
Assume the array primes has been initialized as described in
Self Check 1. What does it contain after executing the
following loop?
for (int i = 0; i < 2; i++)
{
primes[4 - i] = primes[i];
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
Self Check 7.3
Answer: 3, 4, 6, 8, 12
 Assume the array primes has been initialized as described
in Self Check 1. What does it contain after executing the
following loop?
for (int i = 0; i < 5; i++)
{
primes[i]++;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
Self Check 7.4
Answer:
values[0] = 10;
values[9] = 10;
or better:
values[values.length - 1] = 10;
Given the declaration
int[] values = new int[10];
write statements to put the integer 10 into the elements of the
array values with the lowest and the highest valid index.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
Self Check 7.5
Answer:
String[] words = new String[10];
Declare an array called words that can hold ten elements of
type String.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Self Check 7.6
Answer:
String[] words = { "Yes", "No" };
 Declare an array containing two strings, "Yes", and "No".
Copyright © 2014 by John Wiley & Sons. All rights reserved. 24
Self Check 7.7
Answer: No. Because you don’t store the values, you need
to print them when you read them. But you don’t know
where to add the <= until you have seen all values.
 Can you produce the output on page 312 without storing the inputs in an
array, by using an algorithm similar to the algorithm for finding the maximum
in Section 6.7.5?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 25
Self Check 7.8
Answer:
public class Lottery
{
public int[] getCombination(int n) { . . . }
. . .
}
 Declare a method of a class Lottery that returns a
combination of n numbers. You don’t need to implement the
method.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 26
Make Parallel Arrays into Arrays of Objects
 Don't do this
int[] accountNumbers;
double[] balances;
 Don't use parallel arrays
Figure 4
Copyright © 2014 by John Wiley & Sons. All rights reserved. 27
Make Parallel Arrays into Arrays of Objects
Avoid parallel arrays by changing them into arrays of objects:
BankAccount[] accounts;
Figure 5
Copyright © 2014 by John Wiley & Sons. All rights reserved. 28
The Enhanced for Loop
 You can use the enhanced for loop to visit all elements of an
array.
 Totaling the elements in an array with the enhanced for loop
double[] values = . . .;
double total = 0;
for (double element : values)
{
total = total + element;
}
 The loop body is executed for each element in the array values.
 Read the loop as “for each element in values”.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 29
The Enhanced for Loop
 Traditional alternative:
for (int i = 0; i < values.length; i++)
{
double element = values[i];
total = total + element;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 30
The Enhanced for Loop
 Not suitable for all array algorithms.
 Does not allow you to modify the contents of an array.
 The following loop does not fill an array with zeros:
for (double element : values)
{
element = 0;
// ERROR: this assignment does not modify
// array elements
}
 Use a basic for loop instead:
for (int i = 0; i < values.length; i++)
{
values[i] = 0; // OK
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 31
The Enhanced for Loop
 Use the enhanced for loop if you do not need the index values
in the loop body.
 The enhanced for loop is a convenient mechanism for
traversing all elements in a collection.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 32
Syntax 7.2 The Enhanced for Loop
Copyright © 2014 by John Wiley & Sons. All rights reserved. 33
Self Check 7.9
Answer: It counts how many elements of values are zero.
What does this enhanced for loop do?
int counter = 0;
for (double element : values)
{
if (element == 0) { counter++; }
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34
Self Check 7.10
Answer:
for (double x : values)
{
System.out.println(x);
}
Write an enhanced for loop that prints all elements in the array
values.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 35
Self Check 7.11
Answer: The loop writes a value into values[i]. The
enhanced for loop does not have the index variable i.
Why is the enhanced for loop not an appropriate shortcut for
the following basic for loop?
for (int i = 0; i < values.length; i++)
{
values[i] = i * i;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 36
Common Array Algorithm: Filling
 Fill an array with squares (0, 1, 4, 9, 16, ...):
for (int i = 0; i < values.length; i++)
{
values[i] = i * i;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 37
Common Array Algorithm: Maximum or
Minimum
 Finding the maximum in an array
double largest = values[0];
for (int i = 1; i < values.length; i++)
{
if (values[i] > largest)
{
largest = values[i];
}
}
 The loop starts at 1 because we initialize largest with values[0].
Copyright © 2014 by John Wiley & Sons. All rights reserved. 38
Common Array Algorithm: Maximum or
Minimum
 Finding the minimum: reverse the comparison.
 These algorithms require that the array contain at least one
element.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 39
Common Array Algorithm: Element
Separators
 When you display the elements of an array, you usually want to
separate them:
Ann | Bob | Cindy
 Note that there is one fewer separator than there are elements
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
Common Array Algorithm: Element
Separators
 Print the separator before each element except the initial one
(with index 0):
for (int i = 0; i < names.size(); i++)
{
if (i > 0) { System.out.print(" | "); }
System.out.print(names.value[i]);
}
 To print five elements, you need four separators.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 41
Common Array Algorithm: Linear Search
 To find the position of an element:
• Visit all elements until you have found a match or you have come to the
end of the array
 Example: Find the first element that is equal to 100
int searchedValue = 100;
int pos = 0;
boolean found = false;
while (pos < values.length && !found)
{
if (values[pos] == searchedValue) { found = true; }
else { pos++; }
}
if (found) { System.out.println("Found at position: " + pos); }
else { System.out.println("Not found"); }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 42
Common Array Algorithm: Linear Search
 This algorithm is called a linear search.
 A linear search inspects elements in sequence until a match is
found.
 To search for a specific element, visit the elements and stop
when you encounter the match.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
Common Array Algorithm: Removing an
Element
Problem: To remove the element with index pos from the array
values with number of elements currentSize.
 Unordered
1. Overwrite the element to be removed with the last element of the array.
2. Decrement the currentSize variable.
values[pos] = values[currentSize - 1];
currentSize--;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 44
Common Array Algorithm: Removing an
Element
Figure 6 Removing an Element in an Unordered Array
Copyright © 2014 by John Wiley & Sons. All rights reserved. 45
Common Array Algorithm: Removing an
Element
 Ordered array
1. Move all elements following the element to be removed to a lower index.
2. Decrement the variable holding the size of the array.
for (int i = pos + 1; i < currentSize; i++)
{
values[i - 1] = values[i];
}
currentSize--;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 46
Common Array Algorithm: Removing an
Element
Figure 7 Removing an Element in an Ordered Array
Copyright © 2014 by John Wiley & Sons. All rights reserved. 47
Common Array Algorithm: Inserting an
Element
 If order does not matter
1. Insert the new element at the end of the array.
2. Increment the variable tracking the size of the array.
if (currentSize < values.length)
{
currentSize++;
values[currentSize -1 ] = newElement;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 48
Common Array Algorithm: Inserting an
Element
Figure 8 Inserting an Element in an Unordered Array
Copyright © 2014 by John Wiley & Sons. All rights reserved. 49
Common Array Algorithm: Inserting an
Element
 If order matters Increment the variable tracking the size of the array.
1. Move all elements after the insertion location to a higher index.
2. Insert the element.
if (currentSize < values.length)
{
currentSize++;
for (int i = currentSize - 1; i > pos; i--)
{
values[i] = values[i - 1];
}
values[pos] = newElement;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 50
Common Array Algorithm: Inserting an
Element
Figure 9 Inserting an Element in an Ordered Array
Copyright © 2014 by John Wiley & Sons. All rights reserved. 51
Common Array Algorithm: Swapping
Elements
 To swap two elements, you need a temporary variable.
 We need to save the first value in the temporary variable before
replacing it.
double temp = values[i];
values[i] = values[j];
 Now we can set values[j] to the saved value.
values[j] = temp;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 52
Common Array Algorithm: Swapping
Elements
Figure 10 Swapping Array Elements
Copyright © 2014 by John Wiley & Sons. All rights reserved. 53
Common Array Algorithm: Copying an Array
 Copying an array variable yields a second reference to the
same array:
double[] values = new double[6];
. . . // Fill array
double[] prices = values;
 To make a true copy of an array, call the Arrays.copyOf method:
double[] prices =
Arrays.copyOf(values, values.length);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
Common Array Algorithm: Copying an Array
Figure 11 Copying an Array Reference versus Copying an Array
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
Common Array Algorithm: Growing an Array
 To grow an array that has run out of space, use the
Arrays.copyOf method to double the length of an array
double[] newValues = Arrays.copyOf(values, 2 * values.length);
values = newValues;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
Common Array Algorithm: Growing an Array
Figure 12 Growing an Array
Copyright © 2014 by John Wiley & Sons. All rights reserved. 57
Reading Input
 To read a sequence of arbitrary length:
• Add the inputs to an array until the end of the input has been reached.
• Grow when needed.
double[] inputs = new double[INITIAL_SIZE];
int currentSize = 0;
while (in.hasNextDouble())
{
// Grow the array if it has been completely filled
if (currentSize >= inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length); // Grow the inputs array
}
inputs[currentSize] = in.nextDouble(); currentSize++;
}
• Discard unfilled elements.
inputs = Arrays.copyOf(inputs, currentSize);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 58
section_3/LargestInArray.java
1 import java.util.Scanner;
2
3 /**
4 This program reads a sequence of values and prints them, marking the largest value.
5 */
6 public class LargestInArray
7 {
8 public static void main(String[] args)
9 {
10 final int LENGTH = 100;
11 double[] values = new double[LENGTH];
12 int currentSize = 0;
13
14 // Read inputs
15
16 System.out.println("Please enter values, Q to quit:");
17 Scanner in = new Scanner(System.in);
18 while (in.hasNextDouble() && currentSize < values.length)
19 {
20 values[currentSize] = in.nextDouble();
21 currentSize++;
22 }
23
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 59
section_3/LargestInArray.java
24 // Find the largest value
25
26 double largest = values[0];
27 for (int i = 1; i < currentSize; i++)
28 {
29 if (values[i] > largest)
30 {
31 largest = values[i];
32 }
33 }
34
35 // Print all values, marking the largest
36
37 for (int i = 0; i < currentSize; i++)
38 {
39 System.out.print(values[i]);
40 if (values[i] == largest)
41 {
42 System.out.print(" <== largest value");
43 }
44 System.out.println();
45 }
46 }
47 }
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 60
section_3/LargestInArray.java
Program Run
Please enter values, Q to quit: 34.5 80 115 44.5 Q
34.5
80
115 <== largest value
44.5
Copyright © 2014 by John Wiley & Sons. All rights reserved. 61
Self Check 7.13
Answer:
20 <== largest value
10
20 <== largest value
Given these inputs, what is the output of the LargestInArray
program?
20 10 20 Q
Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
Self Check 7.14
Answer:
int count = 0;
for (double x : values)
{
if (x == 0) { count++; }
}
Write a loop that counts how many elements in an array are equal
to zero.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 63
Self Check 7.15
Answer: If all elements of values are negative, then the
result is incorrectly computed as 0.
Consider the algorithm to find the largest element in an array. Why
don’t we initialize largest and i with zero, like this?
double largest = 0;
for (int i = 0; i < values.length; i++)
{
if (values[i] > largest) { largest = values[i]; }
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 64
Self Check 7.16
Answer:
for (int i = 0; i < values.length; i++)
{
System.out.print(values[i]);
if (i < values.length – 1)
{
System.out.print(" | ");
}
}
Now you know why we set up the loop the other way.
When printing separators, we skipped the separator before the
initial element. Rewrite the loop so that the separator is printed
after each element, except for the last element.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 65
Self Check 7.17
Answer: If the array has no elements, then the program
terminates with an exception.
What is wrong with these statements for printing an array with
separators?
System.out.print(values[0]);
for (int i = 1; i < values.length; i++)
{
System.out.print(", " + values[i]);
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 66
Self Check 7.18
Answer: If there is a match, then pos is incremented
before the loop exits.
When finding the position of a match, we used a while loop, not a
for loop. What is wrong with using this loop instead?
for (pos = 0; pos < values.length && !found; pos++)
{
if (values[pos] > 100) { found = true; }
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 67
Self Check 7.19
Answer: This loop sets all elements to values[pos].
When inserting an element into an array, we moved the elements
with larger index values, starting at the end of the array. Why is
it wrong to start at the insertion location, like this?
for (int i = pos; i < currentSize - 1; i++)
{
values[i + 1] = values[i];
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 68
Problem Solving: Adapting Algorithms
 By combining fundamental algorithms, you can solve complex
programming tasks.
 Problem: Compute the final quiz score by dropping the lowest
and finding the sum of all the remaining scores.
 Related algorithms:
• Calculating the sum
• Finding the minimum value
• Removing an element
Copyright © 2014 by John Wiley & Sons. All rights reserved. 69
Problem Solving: Adapting Algorithms
 A plan of attack
Find the minimum.
Remove it from the array.
Calculate the sum.
 Try it out. The minimum is 4
 We need to use a linear search to find the position of the
minimum.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 70
Problem Solving: Adapting Algorithms
 Revise the plan of attack
Find the minimum value.
Find its position.
Remove that position from the array.
Calculate the sum.
 Try it out
• Find the minimum value of 4. Linear search tells us that the value 4
occurs at position 5.
• Remove it
 Compute the sum: 8 + 7 + 8.5 + 9.5 + 7 + 10 = 50.
 This walk-through demonstrates that our strategy works.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 71
Problem Solving: Adapting Algorithms
 Inefficient to find the minimum and then make another pass
through the array to obtain its position.
 Modify minimum algorithm to remember the position of the
smallest element
int smallestPosition = 0;
for (int i = 1; i < values.length; i++)
{
if (values[i] < values[smallestPosition])
{
smallestPosition = I;
}
}
 Final Strategy
Find the position of the minimum.
Remove it from the array.
Calculate the sum.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 72
Self Check 7.20
Answer: Use the first algorithm. The order of elements
does not matter when computing the sum.
Section 7.3.6 has two algorithms for removing an element. Which
of the two should be used to solve the task described in this
section?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 73
Self Check 7.21
 Answer:
Find the minimum value.
Calculate the sum.
Subtract the minimum value.
It isn’t actually necessary to remove the minimum in order to
compute the total score. Describe an alternative.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 74
Self Check 7.22
Answer: Use the algorithm for counting matches (Section
6.7.2) twice, once for counting the positive values and
once for counting the negative values.
How can you print the number of positive and negative values in a
given array, using one or more of the algorithms in Section 6.7?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 75
Self Check 7.23
Answer: You need to modify the algorithm in Section 7.3.4.
boolean first = true;
for (int i = 0; i < values.length; i++)
{
if (values[i] > 0))
{
if (first) { first = false; }
else { System.out.print(", "); }
}
System.out.print(values[i]);
}
Note that you can no longer use i > 0 as the criterion for
printing a separator.
How can you print all positive values in an array, separated by
commas?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 76
Self Check 7.24
Answer: Use the algorithm to collect all positive elements
in an array, then use the algorithm in Section 7.3.4 to
print the array of matches.
Consider the following algorithm for collecting all matches in an
array:
int matchesSize = 0;
for (int i = 0; i < values.length; i++)
{
if (values[i] fulfills the condition)
{
matches[matchesSize] = values[i];
matchesSize++;
}
}
How can this algorithm help you with Self Check 23?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 77
Problem Solving: Discovering Algorithms by
Manipulating Physical Objects
 Manipulating physical objects can give you ideas for
discovering algorithms.
 The Problem: You are given an array whose size is an even
number, and you are to switch the first and the second half.
 Example
• This array
• will become
Copyright © 2014 by John Wiley & Sons. All rights reserved. 78
Problem Solving: Discovering Algorithms by
Manipulating Physical Objects
 Use a sequence of coins, playing cards, or toys to visualize an
array of values.
 Original line of coins
 Removal of an array element
 Insertion of an array element
Copyright © 2014 by John Wiley & Sons. All rights reserved. 79
Problem Solving: Discovering Algorithms by
Manipulating Physical Objects
 Swapping array elements
 Swap the coins in positions 0 and 4:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 80
Problem Solving: Discovering Algorithms by
Manipulating Physical Objects
 Swap the coins in positions 1 and 5:
 Two more swaps
Copyright © 2014 by John Wiley & Sons. All rights reserved. 81
Problem Solving: Discovering Algorithms by
Manipulating Physical Objects
 The pseudocode
i = 0 j = size / 2
While (i < size / 2)
Swap elements at positions i and j
i++
j++
Copyright © 2014 by John Wiley & Sons. All rights reserved. 82
Self Check 7.25
Answer: The paperclip for i assumes positions 0, 1, 2, 3. When i
is incremented to 4, the condition
i < size / 2
becomes false, and the loop ends. Similarly, the paperclip for j
assumes positions 4, 5, 6, 7, which are the valid positions for
the second half of the array.
Walk through the algorithm that we developed in this section,
using two paper clips to indicate the positions for i and j.
Explain why there are no bounds errors in the pseudocode.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 83
Self Check 7.26
Answer: It reverses the elements in the array.
Take out some coins and simulate the following pseudocode,
using two paper clips to indicate the positions for i and j.
i = 0
j = size – 1
While (i < j)
Swap elements at positions i and j
i++
j--
What does the algorithm do?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 84
Self Check 7.27
Consider the task of rearranging all elements in an array so that
the even numbers come first. Otherwise, the order doesn’t
matter. For example, the array
1 4 14 2 1 3 5 6 23
could be rearranged to
4 2 14 6 1 5 3 23 1
Using coins and paperclips, discover an algorithm that solves this
task by swapping elements, then describe it in pseudocode.
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 85
Self Check 7.27
Answer: Here is one solution. The basic idea is to move all odd
elements to the end. Put one paper clip at the beginning of the array
and one at the end. If the element at the first paper clip is odd, swap
it with the one at the other paper clip and move that paper clip to the
left. Otherwise, move the first paper clip to the right. Stop when the
two paper clips meet. Here is the pseudocode:
i = 0
j = size – 1
While (i < j)
If (a[i] is odd)
Swap elements at positions i and j.
j--
Else
i++
Copyright © 2014 by John Wiley & Sons. All rights reserved. 86
Self Check 7.28
Answer: Here is one solution. The idea is to remove all
odd elements and move them to the end. The trick is to
know when to stop. Nothing is gained by moving odd
elements into the area that already contains moved
elements, so we want to mark that area with another
paper clip.
i = 0
moved = size
While (i < moved)
If (a[i] is odd)
Remove the element at position i and add it at the end.
moved--
 Discover an algorithm for the task of Self Check 27 that uses
removal and insertion of elements instead of swapping.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 87
Self Check 7.29
Answer: When you read inputs, you get to see values one
at a time, and you can’t peek ahead. Picking cards one
at a time from a deck of cards simulates this process
better than looking at a sequence of items, all of which
are revealed.
Consider the algorithm in Section 6.7.5 that finds the largest
element in a sequence of inputs—not the largest element in an
array. Why is this algorithm better visualized by picking playing
cards from a deck rather than arranging toy soldiers in a
sequence?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 88
Two-Dimensional Arrays
 An arrangement consisting of rows and columns of values
• Also called a matrix.
 Example: medal counts of the figure skating competitions at the 2010
Winter Olympics.
Figure 13 Figure Skating Medal counts
Copyright © 2014 by John Wiley & Sons. All rights reserved. 89
Two-Dimensional Arrays
 Use a two-dimensional array to store tabular data.
 When constructing a two-dimensional array, specify how many
rows and columns are needed:
final int COUNTRIES = 7;
final int MEDALS = 3;
int[][] counts = new int[COUNTRIES][MEDALS];
Copyright © 2014 by John Wiley & Sons. All rights reserved. 90
Two-Dimensional Arrays
 You can declare and initialize the array by grouping each row:
int[][] counts =
{
{ 1, 0, 1 },
{ 1, 1, 0 },
{ 0, 0, 1 },
{ 1, 0, 0 },
{ 0, 1, 1 },
{ 0, 1, 1 },
{ 1, 1, 0 }
};
 You cannot change the size of a two-dimensional array once it
has been declared.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 91
Syntax 7.3 Two-Dimensional Array Declaration
Copyright © 2014 by John Wiley & Sons. All rights reserved. 92
Accessing Elements
 Access by using two index values, array[i][j]
int medalCount = counts[3][1];
 Use nested loops to access all elements in a two-dimensional
array.
 Example: print all the elements of the counts array
for (int i = 0; i < COUNTRIES; i++)
{
// Process the ith row
for (int j = 0; j < MEDALS; j++)
{
// Process the jth column in the ith row
System.out.printf("%8d", counts[i][j]);
}
System.out.println(); // Start a new line at the end of the row
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 93
Accessing Elements
Figure 14 Accessing an Element in a Two-Dimensional Array
Copyright © 2014 by John Wiley & Sons. All rights reserved. 94
Accessing Elements
 Number of rows: counts.length
 Number of columns: counts[0].length
 Example: print all the elements of the counts array
for (int i = 0; i < counts.length; i++)
{
for (int j = 0; j < counts[0].length; j++)
{
System.out.printf("%8d", counts[i][j]);
}
System.out.println();
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 95
Locating Neighboring Elements
Figure 15 Neighboring Locations in a Two-Dimensional Array
 Watch out for elements at the boundary array
• counts[0][1] does not have a neighbor to the top
Copyright © 2014 by John Wiley & Sons. All rights reserved. 96
Accessing Rows and Columns
 Problem: To find the number of medals won by a country
• Find the sum of the elements in a row
 To find the sum of the ith row
• compute the sum of counts[i][j], where j ranges from 0 to MEDALS - 1.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 97
Accessing Rows and Columns
 Loop to compute the sum of the ith row
int total = 0;
for (int j = 0; j < MEDALS; j++)
{
total = total + counts[i][j];
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 98
Accessing Rows and Columns
 To find the sum of the jth column
• Form the sum of counts[i][j], where i ranges from 0 to COUNTRIES – 1
int total = 0;
for (int i = 0; i < COUNTRIES; i++
{
total = total + counts[i][j];
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 99
section_6/Medals.java
1 /**
2 This program prints a table of medal winner counts with row totals.
3 */
4 public class Medals
5 {
6 public static void main(String[] args)
7 {
8 final int COUNTRIES = 7;
9 final int MEDALS = 3;
10
11 String[] countries =
12 {
13 "Canada",
14 "China",
15 "Germany",
16 "Korea",
17 "Japan",
18 "Russia",
19 "United States"
20 };
21
22 int[][] counts =
23 {
24 { 1, 0, 1 },
25 { 1, 1, 0 },
26 { 0, 0, 1 },
27 { 1, 0, 0 },
28 { 0, 1, 1 },
29 { 0, 1, 1 },
30 { 1, 1, 0 }
31 };
32
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 100
section_6/Medals.java
33 System.out.println(" Country Gold Silver Bronze Total");
34
35 // Print countries, counts, and row totals
36 for (int i = 0; i < COUNTRIES; i++)
37 {
38 // Process the ith row
39 System.out.printf("%15s", countries[i]);
40
41 int total = 0;
42
43 // Print each row element and update the row total
44 for (int j = 0; j < MEDALS; j++)
45 {
46 System.out.printf("%8d", counts[i][j]);
47 total = total + counts[i][j];
48 }
49
50 // Display the row total and print a new line
51 System.out.printf("%8dn", total);
52 }
53 }
54 }
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 101
section_6/Medals.java
Program Run
Copyright © 2014 by John Wiley & Sons. All rights reserved. 102
Self Check 7.30
Answer: You get the total number of gold, silver, and bronze
medals in the competition. In our example, there are four of
each.
What results do you get if you total the columns in our sample
data?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 103
Self Check 7.31
Consider an 8 × 8 array for a board game:
int[][] board = new int[8][8];
Using two nested loops, initialize the board so that
zeros and ones alternate, as on a checkerboard:
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
. . .
1 0 1 0 1 0 1 0
Hint: Check whether i + j is even.
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 104
Self Check 7.31
Answer:
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
board[i][j] = (i + j) % 2;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 105
Self Check 7.32
Answer:
String[][] board = new String[3][3];
Declare a two-dimensional array for representing a tic-tac-toe
board. The board has three rows and columns and contains
strings "x", "o", and " ".
Copyright © 2014 by John Wiley & Sons. All rights reserved. 106
Self Check 7.33
Answer:
board[0][2] = "x";
Write an assignment statement to place an "x" in the upper-right corner
of the tic-tac-toe board in Self Check 32.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 107
Self Check 7.34
Answer: board[0][0], board[1][1], board[2][2]
Which elements are on the diagonal joining the upper-left and the
lower-right corners of the tic-tac-toe board in Self Check 32?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 108
Array Lists
 An array list stores a sequence of values whose size can
change.
 An array list can grow and shrink as needed.
 ArrayList class supplies methods for many common tasks, such
as inserting and removing elements.
 An array list expands to hold as many elements as needed.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 109
Syntax 7.4 Array Lists
Copyright © 2014 by John Wiley & Sons. All rights reserved. 110
Declaring and Using Array Lists
 To declare an array list of strings
ArrayList<String> names = new ArrayList<String>();
 To use an array list
import java.util.ArrayList;
 ArrayList is a generic class
 Angle brackets denote a type parameter
• Replace String with any other class to get a different array list type
Copyright © 2014 by John Wiley & Sons. All rights reserved. 111
Declaring and Using Array Lists
 ArrayList<String> is first constructed, it has size 0
 Use the add method to add an object to the end of the array list:
names.add("Emily"); // Now names has size 1 and element "Emily”
names.add("Bob"); // Now names has size 2 and elements "Emily", "Bob”
names.add("Cindy"); // names has size 3 and elements "Emily", "Bob",
// and "Cindy”
 The size method gives the current size of the array list.
• Size is now 3
Figure 17 Adding an Array List Element with add
Copyright © 2014 by John Wiley & Sons. All rights reserved. 112
Declaring and Using Array Lists
 To obtain an array list element, use the get method
• Index starts at 0
 To retrieve the name with index 2:
String name = names.get(2); // Gets the third element
// of the array list
 The last valid index is names.size() - 1
• A common bounds error:
int i = names.size();
name = names.get(i); // Error
 To set an array list element to a new value, use the set method:
names.set(2, "Carolyn");
Copyright © 2014 by John Wiley & Sons. All rights reserved. 113
Declaring and Using Array Lists
 An array list has methods for adding and removing elements in
the middle.
 This statement adds a new element at position 1 and moves all
elements with index 1 or larger by one position.
names.add(1, "Ann");
Copyright © 2014 by John Wiley & Sons. All rights reserved. 114
Declaring and Using Array Lists
 The remove method,
• removes the element at a given position
• moves all elements after the removed element down by one position
• and reduces the size of the array list by 1.
names.remove(1);
 To print an array list:
System.out.println(names);
// Prints [Emily, Bob, Carolyn]
Copyright © 2014 by John Wiley & Sons. All rights reserved. 115
Declaring and Using Array Lists
Figure 18 Adding and Removing Elements in the Middle of an
Array List
Copyright © 2014 by John Wiley & Sons. All rights reserved. 116
Using the Enhanced for Loop with Array
Lists
 You can use the enhanced for loop to visit all the elements of
an array list
ArrayList<String> names = . . . ;
for (String name : names)
{
System.out.println(name);
}
 This is equivalent to:
for (int i = 0; i < names.size(); i++)
{
String name = names.get(i);
System.out.println(name);
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 117
Copying Array Lists
 Copying an array list reference yields two references to the
same array list.
 After the code below is executed
• Both names and friends reference the same array list to which the string
"Harry" was added.
ArrayList<String> friends = names;
friends.add("Harry");
Figure 19 Copying an Array List Reference
Copyright © 2014 by John Wiley & Sons. All rights reserved. 118
Copying Array Lists
 To make a copy of an array list, construct the copy and pass the
original list into the constructor:
ArrayList<String> newNames =
new ArrayList<String>(names);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 119
Working With Array Lists
Copyright © 2014 by John Wiley & Sons. All rights reserved. 120
Wrapper Classes
 You cannot directly insert primitive type values into array lists.
 Like truffles that must be in a wrapper to be sold, a number
must be placed in a wrapper to be stored in an array list.
 Use the matching wrapper class.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 121
Wrapper Classes
 To collect double values in an array list, you use an
ArrayList<Double>.
 If you assign a double value to a Double variable, the number is
automatically “put into a box”
 Called auto-boxing:
• Automatic conversion between primitive types and the corresponding
wrapper classes:
Double wrapper = 29.95;
• Wrapper values are automatically “unboxed” to primitive types
double x = wrapper;
Figure 20 A Wrapper Class Variable
Copyright © 2014 by John Wiley & Sons. All rights reserved. 122
Using Array Algorithms with Array Lists
 The array algorithms can be converted to array lists simply by
using the array list methods instead of the array syntax.
 Code to find the largest element in an array:
double largest = values[0];
for (int i = 1; i < values.length; i++)
{
if (values[i] > largest) { largest = values[i]; }
}
 Code to find the largest element in an array list:
double largest = values.get(0);
for (int i = 1; i < values.size(); i++)
{
if (values.get(i) > largest) { largest = values.get(i); }
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 123
Storing Input Values in an Array List
 To collect an unknown number of inputs, array lists are much
easier to use than arrays.
 Simply read the inputs and add them to an array list:
ArrayList<Double> inputs = new ArrayList<Double>();
while (in.hasNextDouble())
{
inputs.add(in.nextDouble());
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 124
Removing Matches
 To remove elements from an array list, call the remove method.
 Error: skips the element after the moved element
ArrayList<String> words = ...;
for (int i = 0; i < words.size(); i++)
{
String word = words.get(i);
if (word.length() < 4)
{
Remove the element at index i.
}
}
 Concrete example
Copyright © 2014 by John Wiley & Sons. All rights reserved. 125
Removing Matches
 Should not increment i when an element is removed
 Pseudocode
If the element at index i matches the condition
Remove the element.
Else
Increment i.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 126
Removing Matches
 Use a while loop, not a for loop
int i = 0;
while (i < words.size())
{
String word = words.get(i);
if (word.length() < 4) { words.remove(i); }
else { i++; }
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 127
Choosing Between Array Lists and Arrays
 For most programming tasks, array lists are easier to use than
arrays
• Array lists can grow and shrink.
• Arrays have a nicer syntax.
 Recommendations
• If the size of a collection never changes, use an array.
• If you collect a long sequence of primitive type values and you are
concerned about efficiency, use an array.
• Otherwise, use an array list.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 128
Choosing Between Array Lists and Arrays
Copyright © 2014 by John Wiley & Sons. All rights reserved. 129
section_7/LargestInArrayList.java
1 import java.util.ArrayList;
2 import java.util.Scanner;
3
4 /**
5 This program reads a sequence of values and prints them, marking the largest value.
6 */
7 public class LargestInArrayList
8 {
9 public static void main(String[] args)
10 {
11 ArrayList<Double> values = new ArrayList<Double>();
12
13 // Read inputs
14
15 System.out.println("Please enter values, Q to quit:");
16 Scanner in = new Scanner(System.in);
17 while (in.hasNextDouble())
18 {
19 values.add(in.nextDouble());
20 }
21
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 130
section_7/LargestInArrayList.java
22 // Find the largest value
23
24 double largest = values.get(0);
25 for (int i = 1; i < values.size(); i++)
26 {
27 if (values.get(i) > largest)
28 {
29 largest = values.get(i);
30 }
31 }
32
33 // Print all values, marking the largest
34
35 for (double element : values)
36 {
37 System.out.print(element);
38 if (element == largest)
39 {
40 System.out.print(" <== largest value");
41 }
42 System.out.println();
43 }
44 }
45 }
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 131
section_7/LargestInArrayList.java
Program Run
Please enter values, Q to quit:
35 80 115 44.5 Q
35
80
115 <== largest value
44.5
Copyright © 2014 by John Wiley & Sons. All rights reserved. 132
Self Check 7.35
Answer:
ArrayList<Integer> primes =
new ArrayList<Integer>();
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
primes.add(11);
Declare an array list primes of integers that contains the first five
prime numbers (2, 3, 5, 7, and 11).
Copyright © 2014 by John Wiley & Sons. All rights reserved. 133
Self Check 7.36
Answer:
for (int i = primes.size() - 1; i >= 0; i--)
{
System.out.println(primes.get(i));
}
Given the array list primes declared in Self Check 35, write a loop
to print its elements in reverse order, starting with the last
element.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 134
Self Check 7.37
Answer: "Ann", "Cal"
What does the array list names contain after the following
statements?
ArrayList<String> names = new ArrayList<String>;
names.add("Bob");
names.add(0, "Ann");
names.remove(1);
names.add("Cal");
Copyright © 2014 by John Wiley & Sons. All rights reserved. 135
Self Check 7.38
Answer: The names variable has not been initialized.
What is wrong with this code snippet?
ArrayList<String> names;
names.add(Bob);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 136
Self Check 7.39
Consider this method that appends the elements of one array list to
another:
public void append(ArrayList<String> target,
ArrayList<String> source)
{
for (int i = 0; i < source.size(); i++)
{
target.add(source.get(i));
}
}
What are the contents of names1 and names2 after these statements?
ArrayList<String> names1 = new ArrayList<String>();
names1.add("Emily");
names1.add("Bob");
names1.add("Cindy");
ArrayList<String> names2 = new ArrayList<String>();
names2.add("Dave");
append(names1, names2);
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 137
Self Check 7.39
Answer: names1 contains "Emily", "Bob", "Cindy", "Dave";
names2 contains "Dave"
Copyright © 2014 by John Wiley & Sons. All rights reserved. 138
Self Check 7.40
Answer: Because the number of weekdays doesn’t change,
there is no disadvantage to using an array, and it is easier
to initialize:
String[] weekdayNames = { "Monday", "Tuesday",
"Wednesday", "Thursday", “Friday”, "Saturday",
"Sunday" };
Suppose you want to store the names of the weekdays. Should
you use an array list or an array of seven strings?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 139
Self Check 7.41
Answer: Reading inputs into an array list is much easier.
The ch07/section_7 directory of your source code contains an
alternate implementation of the problem solution in How To 7.1
on page 334. Compare the array and array list
implementations. What is the primary advantage of the latter?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 140
Regression Testing
 Test suite: a set of tests for repeated testing
 Cycling: bug that is fixed but reappears in later versions
 Regression testing: involves repeating previously run tests to
ensure that known failures of prior versions do not appear in
new versions
Copyright © 2014 by John Wiley & Sons. All rights reserved. 141
Regression Testing – Two Approaches
 Organize a suite of test with multiple tester classes: ScoreTester1,
ScoreTester2, …
public class ScoreTester1
{
public static void main(String[] args)
{
Student fred = new Student(100);
fred.addScore(10);
fred.addScore(20);
fred.addScore(5);
System.out.println("Final score: " + fred.finalScore());
System.out.println("Expected: 30");
}
}
 Provide a generic tester, and feed it inputs from multiple files.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 142
section_8/ScoreTester.java
generic tester
1 import java.util.Scanner;
2
3 public class ScoreTester
4 {
5 public static void main(String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8 double expected = in.nextDouble();
9 Student fred = new Student(100);
10 while (in.hasNextDouble())
11 {
12 if (!fred.addScore(in.nextDouble()))
13 {
14 System.out.println("Too many scores.");
15 return;
16 }
17 }
18 System.out.println("Final score: " + fred.finalScore());
19 System.out.println("Expected: " + expected);
20 }
21 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 143
Input and Output Redirection
 Section_8/input1.txt contains:
30
10
20
5
 Type the following command into a shell window
• Input redirection
java ScoreTester < input1.txt
 Program Run:
Final score: 30
Expected: 30
 Output redirection:
java ScoreTester < input1.txt > output1.txt
Copyright © 2014 by John Wiley & Sons. All rights reserved. 144
Self Check 7.42
Answer: It is possible to introduce errors when modifying
code.
Suppose you modified the code for a method. Why do you want to
repeat tests that already passed with the previous version of
the code?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 145
Self Check 7.43
Answer: Add a test case to the test suite that verifies that the
error is fixed.
Suppose a customer of your program finds an error. What action
should you take beyond fixing the error?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 146
Self Check 7.44
Answer: There is no human user who would see the prompts
because input is provided from a file.
Why doesn't the ScoreTester program contain prompts for the
inputs?

More Related Content

PPTX
Icom4015 lecture7-f16
PPTX
Icom4015 lecture14-f16
PPTX
CiIC4010-chapter-2-f17
PPTX
Icom4015 lecture15-f16
PPTX
Icom4015 lecture3-f16
PPTX
Icom4015 lecture13-f16
PPTX
Icom4015 lecture4-f16
PPTX
Icom4015 lecture4-f17
Icom4015 lecture7-f16
Icom4015 lecture14-f16
CiIC4010-chapter-2-f17
Icom4015 lecture15-f16
Icom4015 lecture3-f16
Icom4015 lecture13-f16
Icom4015 lecture4-f16
Icom4015 lecture4-f17

What's hot (20)

PPTX
Icom4015 lecture9-f16
PPTX
Icom4015 lecture10-f16
PPTX
Icom4015 lecture8-f16
PPTX
Icom4015 lecture3-f17
PPTX
Icom4015 lecture12-s16
PPTX
Icom4015 lecture3-s18
PPTX
CIIC 4010 Chapter 1 f17
PPTX
Icom4015 lecture3-f17
PPTX
Advanced Programming Lecture 5 Fall 2016
PPTX
Icom4015 lecture11-s16
PPTX
Intro To C++ - Class #18: Vectors & Arrays
PPT
PPT
Java™ (OOP) - Chapter 6: "Arrays"
PPT
Array in Java
PDF
An Introduction to Programming in Java: Arrays
PPT
Chapter 2 - Getting Started with Java
PPT
Chapter 4 - Defining Your Own Classes - Part I
PPTX
Array lecture
PDF
Arrays in Java | Edureka
PPT
Icom4015 lecture9-f16
Icom4015 lecture10-f16
Icom4015 lecture8-f16
Icom4015 lecture3-f17
Icom4015 lecture12-s16
Icom4015 lecture3-s18
CIIC 4010 Chapter 1 f17
Icom4015 lecture3-f17
Advanced Programming Lecture 5 Fall 2016
Icom4015 lecture11-s16
Intro To C++ - Class #18: Vectors & Arrays
Java™ (OOP) - Chapter 6: "Arrays"
Array in Java
An Introduction to Programming in Java: Arrays
Chapter 2 - Getting Started with Java
Chapter 4 - Defining Your Own Classes - Part I
Array lecture
Arrays in Java | Edureka
Ad

Similar to Advanced Programming Lecture 6 Fall 2016 (20)

PPT
Md05 arrays
PPT
Cso gaddis java_chapter8
PPT
Eo gaddis java_chapter_07_5e
PPT
Cso gaddis java_chapter8
PPTX
C_Arrays(3)bzxhgvxgxg.xhjvxugvxuxuxuxvxugvx.pptx
PDF
Week06
PPTX
Chapter 7.1
PDF
Learn Java Part 8
PPT
Arrays JavaScript presentacion en power point
PPT
Arrays in Java Programming Language slides
PPTX
Arrays in programming
PPTX
array is a fundamental data structure that stores a collection of elements.pptx
PPTX
Introduction To Practical Computer Science I - Lec 12 (Arrays).pptx
PPTX
Module 7 : Arrays
PDF
Lecture 6 - Arrays
PPTX
arrays-120712074248-phpapp01
PDF
Java arrays (1)
PPTX
C++ programming (Array)
PPT
Array
Md05 arrays
Cso gaddis java_chapter8
Eo gaddis java_chapter_07_5e
Cso gaddis java_chapter8
C_Arrays(3)bzxhgvxgxg.xhjvxugvxuxuxuxvxugvx.pptx
Week06
Chapter 7.1
Learn Java Part 8
Arrays JavaScript presentacion en power point
Arrays in Java Programming Language slides
Arrays in programming
array is a fundamental data structure that stores a collection of elements.pptx
Introduction To Practical Computer Science I - Lec 12 (Arrays).pptx
Module 7 : Arrays
Lecture 6 - Arrays
arrays-120712074248-phpapp01
Java arrays (1)
C++ programming (Array)
Array
Ad

Recently uploaded (20)

PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
OOP with Java - Java Introduction (Basics)
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Digital Logic Computer Design lecture notes
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Internet of Things (IOT) - A guide to understanding
PPT
Project quality management in manufacturing
PPTX
Sustainable Sites - Green Building Construction
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPT
introduction to datamining and warehousing
PPTX
Geodesy 1.pptx...............................................
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
CYBER-CRIMES AND SECURITY A guide to understanding
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
OOP with Java - Java Introduction (Basics)
Embodied AI: Ushering in the Next Era of Intelligent Systems
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Digital Logic Computer Design lecture notes
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Internet of Things (IOT) - A guide to understanding
Project quality management in manufacturing
Sustainable Sites - Green Building Construction
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
introduction to datamining and warehousing
Geodesy 1.pptx...............................................
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Model Code of Practice - Construction Work - 21102022 .pdf

Advanced Programming Lecture 6 Fall 2016

  • 1. Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter 7 – Arrays and Array Lists
  • 2. Copyright © 2014 by John Wiley & Sons. All rights reserved. 2 Chapter Goals  To collect elements using arrays and array lists  To use the enhanced for loop for traversing arrays and array lists  To learn common algorithms for processing arrays and array lists  To work with two-dimensional arrays  To understand the concept of regression testing
  • 3. Copyright © 2014 by John Wiley & Sons. All rights reserved. 3 Arrays  An array collects a sequence of values of the same type.  Create an array that can hold ten values of type double: new double[10] • The number of elements is the length of the array • The new operator constructs the array  The type of an array variable is the type of the element to be stored, followed by [].
  • 4. Copyright © 2014 by John Wiley & Sons. All rights reserved. 4 Arrays  To declare an array variable of type double[] double[] values;  To initialize the array variable with the array: double[] values = new double[10];  By default, each number in the array is 0  You can specify the initial values when you create the array double[] moreValues = { 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 };
  • 5. Copyright © 2014 by John Wiley & Sons. All rights reserved. 5 Arrays  To access a value in an array, specify which “slot” you want to use • use the [] operator values[4] = 35;  The “slot number” is called an index.  Each slot contains an element.  Individual elements are accessed by an integer index i, using the notation array[i].  An array element can be used like any variable. System.out.println(values[4]);
  • 6. Copyright © 2014 by John Wiley & Sons. All rights reserved. 6 Arrays Figure 1 An Array of Size 10
  • 7. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 Syntax 7.1 Arrays
  • 8. Copyright © 2014 by John Wiley & Sons. All rights reserved. 8 Arrays  The elements of arrays are numbered starting at 0.  The following declaration creates an array of 10 elements: double[] values = new double[10];  An index can be any integer ranging from 0 to 9.  The first element is values[0]  The last element is values[9]  An array index must be at least zero and less than the size of the array.  Like a mailbox that is identified by a box number, an array element is identified by an index.
  • 9. Copyright © 2014 by John Wiley & Sons. All rights reserved. 9 Arrays – Bounds Error  A bounds error occurs if you supply an invalid array index.  Causes your program to terminate with a run-time error.  Example: double[] values = new double[10]; values[10] = value; // Error  values.length yields the length of the values array.  There are no parentheses following length.
  • 10. Copyright © 2014 by John Wiley & Sons. All rights reserved. 10 Declaring Arrays
  • 11. Copyright © 2014 by John Wiley & Sons. All rights reserved. 11 Array References  An array reference specifies the location of an array.  Copying the reference yields a second reference to the same array.
  • 12. Copyright © 2014 by John Wiley & Sons. All rights reserved. 12 Array References  When you copy an array variable into another, both variables refer to the same array int[] scores = { 10, 9, 7, 4, 5 }; int[] values = scores; // Copying array reference  You can modify the array through either of the variables: scores[3] = 10; System.out.println(values[3]); // Prints 10 Figure 2 Two Array Variables Referencing the Same Array
  • 13. Copyright © 2014 by John Wiley & Sons. All rights reserved. 13 Using Arrays with Methods  Arrays can occur as method arguments and return values.  An array as a method argument public void addScores(int[] values) { for (int i = 0; i < values.length; i++) { totalScore = totalScore + values[i]; } }  To call this method int[] scores = { 10, 9, 7, 10 }; fred.addScores(scores);  A method with an array return value public int[] getScores()
  • 14. Copyright © 2014 by John Wiley & Sons. All rights reserved. 14 Partially Filled Arrays  Array length = maximum number of elements in array.  Usually, array is partially filled  Define an array larger than you will need final int LENGTH = 100; double[] values = new double[LENGTH];  Use companion variable to keep track of current size: call it currentSize
  • 15. Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 Partially Filled Arrays  A loop to fill the array int currentSize = 0; Scanner in = new Scanner(System.in); while (in.hasNextDouble()) { if (currentSize < values.length) { values[currentSize] = in.nextDouble(); currentSize++; } }  At the end of the loop, currentSize contains the actual number of elements in the array.  Note: Stop accepting inputs when currentSize reaches the array length.
  • 16. Copyright © 2014 by John Wiley & Sons. All rights reserved. 16 Partially Filled Arrays
  • 17. Copyright © 2014 by John Wiley & Sons. All rights reserved. 17 Partially Filled Arrays  To process the gathered array elements, use the companion variable, not the array length: for (int i = 0; i < currentSize; i++) { System.out.println(values[i]); }  With a partially filled array, you need to remember how many elements are filled.
  • 18. Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 Self Check 7.1 Answer: int[] primes = { 2, 3, 5, 7, 11 }; Declare an array of integers containing the first five prime numbers.
  • 19. Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 Self Check 7.2 Answer: 2, 3, 5, 3, 2 Assume the array primes has been initialized as described in Self Check 1. What does it contain after executing the following loop? for (int i = 0; i < 2; i++) { primes[4 - i] = primes[i]; }
  • 20. Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 Self Check 7.3 Answer: 3, 4, 6, 8, 12  Assume the array primes has been initialized as described in Self Check 1. What does it contain after executing the following loop? for (int i = 0; i < 5; i++) { primes[i]++; }
  • 21. Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 Self Check 7.4 Answer: values[0] = 10; values[9] = 10; or better: values[values.length - 1] = 10; Given the declaration int[] values = new int[10]; write statements to put the integer 10 into the elements of the array values with the lowest and the highest valid index.
  • 22. Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 Self Check 7.5 Answer: String[] words = new String[10]; Declare an array called words that can hold ten elements of type String.
  • 23. Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 Self Check 7.6 Answer: String[] words = { "Yes", "No" };  Declare an array containing two strings, "Yes", and "No".
  • 24. Copyright © 2014 by John Wiley & Sons. All rights reserved. 24 Self Check 7.7 Answer: No. Because you don’t store the values, you need to print them when you read them. But you don’t know where to add the <= until you have seen all values.  Can you produce the output on page 312 without storing the inputs in an array, by using an algorithm similar to the algorithm for finding the maximum in Section 6.7.5?
  • 25. Copyright © 2014 by John Wiley & Sons. All rights reserved. 25 Self Check 7.8 Answer: public class Lottery { public int[] getCombination(int n) { . . . } . . . }  Declare a method of a class Lottery that returns a combination of n numbers. You don’t need to implement the method.
  • 26. Copyright © 2014 by John Wiley & Sons. All rights reserved. 26 Make Parallel Arrays into Arrays of Objects  Don't do this int[] accountNumbers; double[] balances;  Don't use parallel arrays Figure 4
  • 27. Copyright © 2014 by John Wiley & Sons. All rights reserved. 27 Make Parallel Arrays into Arrays of Objects Avoid parallel arrays by changing them into arrays of objects: BankAccount[] accounts; Figure 5
  • 28. Copyright © 2014 by John Wiley & Sons. All rights reserved. 28 The Enhanced for Loop  You can use the enhanced for loop to visit all elements of an array.  Totaling the elements in an array with the enhanced for loop double[] values = . . .; double total = 0; for (double element : values) { total = total + element; }  The loop body is executed for each element in the array values.  Read the loop as “for each element in values”.
  • 29. Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 The Enhanced for Loop  Traditional alternative: for (int i = 0; i < values.length; i++) { double element = values[i]; total = total + element; }
  • 30. Copyright © 2014 by John Wiley & Sons. All rights reserved. 30 The Enhanced for Loop  Not suitable for all array algorithms.  Does not allow you to modify the contents of an array.  The following loop does not fill an array with zeros: for (double element : values) { element = 0; // ERROR: this assignment does not modify // array elements }  Use a basic for loop instead: for (int i = 0; i < values.length; i++) { values[i] = 0; // OK }
  • 31. Copyright © 2014 by John Wiley & Sons. All rights reserved. 31 The Enhanced for Loop  Use the enhanced for loop if you do not need the index values in the loop body.  The enhanced for loop is a convenient mechanism for traversing all elements in a collection.
  • 32. Copyright © 2014 by John Wiley & Sons. All rights reserved. 32 Syntax 7.2 The Enhanced for Loop
  • 33. Copyright © 2014 by John Wiley & Sons. All rights reserved. 33 Self Check 7.9 Answer: It counts how many elements of values are zero. What does this enhanced for loop do? int counter = 0; for (double element : values) { if (element == 0) { counter++; } }
  • 34. Copyright © 2014 by John Wiley & Sons. All rights reserved. 34 Self Check 7.10 Answer: for (double x : values) { System.out.println(x); } Write an enhanced for loop that prints all elements in the array values.
  • 35. Copyright © 2014 by John Wiley & Sons. All rights reserved. 35 Self Check 7.11 Answer: The loop writes a value into values[i]. The enhanced for loop does not have the index variable i. Why is the enhanced for loop not an appropriate shortcut for the following basic for loop? for (int i = 0; i < values.length; i++) { values[i] = i * i; }
  • 36. Copyright © 2014 by John Wiley & Sons. All rights reserved. 36 Common Array Algorithm: Filling  Fill an array with squares (0, 1, 4, 9, 16, ...): for (int i = 0; i < values.length; i++) { values[i] = i * i; }
  • 37. Copyright © 2014 by John Wiley & Sons. All rights reserved. 37 Common Array Algorithm: Maximum or Minimum  Finding the maximum in an array double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }  The loop starts at 1 because we initialize largest with values[0].
  • 38. Copyright © 2014 by John Wiley & Sons. All rights reserved. 38 Common Array Algorithm: Maximum or Minimum  Finding the minimum: reverse the comparison.  These algorithms require that the array contain at least one element.
  • 39. Copyright © 2014 by John Wiley & Sons. All rights reserved. 39 Common Array Algorithm: Element Separators  When you display the elements of an array, you usually want to separate them: Ann | Bob | Cindy  Note that there is one fewer separator than there are elements
  • 40. Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 Common Array Algorithm: Element Separators  Print the separator before each element except the initial one (with index 0): for (int i = 0; i < names.size(); i++) { if (i > 0) { System.out.print(" | "); } System.out.print(names.value[i]); }  To print five elements, you need four separators.
  • 41. Copyright © 2014 by John Wiley & Sons. All rights reserved. 41 Common Array Algorithm: Linear Search  To find the position of an element: • Visit all elements until you have found a match or you have come to the end of the array  Example: Find the first element that is equal to 100 int searchedValue = 100; int pos = 0; boolean found = false; while (pos < values.length && !found) { if (values[pos] == searchedValue) { found = true; } else { pos++; } } if (found) { System.out.println("Found at position: " + pos); } else { System.out.println("Not found"); }
  • 42. Copyright © 2014 by John Wiley & Sons. All rights reserved. 42 Common Array Algorithm: Linear Search  This algorithm is called a linear search.  A linear search inspects elements in sequence until a match is found.  To search for a specific element, visit the elements and stop when you encounter the match.
  • 43. Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 Common Array Algorithm: Removing an Element Problem: To remove the element with index pos from the array values with number of elements currentSize.  Unordered 1. Overwrite the element to be removed with the last element of the array. 2. Decrement the currentSize variable. values[pos] = values[currentSize - 1]; currentSize--;
  • 44. Copyright © 2014 by John Wiley & Sons. All rights reserved. 44 Common Array Algorithm: Removing an Element Figure 6 Removing an Element in an Unordered Array
  • 45. Copyright © 2014 by John Wiley & Sons. All rights reserved. 45 Common Array Algorithm: Removing an Element  Ordered array 1. Move all elements following the element to be removed to a lower index. 2. Decrement the variable holding the size of the array. for (int i = pos + 1; i < currentSize; i++) { values[i - 1] = values[i]; } currentSize--;
  • 46. Copyright © 2014 by John Wiley & Sons. All rights reserved. 46 Common Array Algorithm: Removing an Element Figure 7 Removing an Element in an Ordered Array
  • 47. Copyright © 2014 by John Wiley & Sons. All rights reserved. 47 Common Array Algorithm: Inserting an Element  If order does not matter 1. Insert the new element at the end of the array. 2. Increment the variable tracking the size of the array. if (currentSize < values.length) { currentSize++; values[currentSize -1 ] = newElement; }
  • 48. Copyright © 2014 by John Wiley & Sons. All rights reserved. 48 Common Array Algorithm: Inserting an Element Figure 8 Inserting an Element in an Unordered Array
  • 49. Copyright © 2014 by John Wiley & Sons. All rights reserved. 49 Common Array Algorithm: Inserting an Element  If order matters Increment the variable tracking the size of the array. 1. Move all elements after the insertion location to a higher index. 2. Insert the element. if (currentSize < values.length) { currentSize++; for (int i = currentSize - 1; i > pos; i--) { values[i] = values[i - 1]; } values[pos] = newElement; }
  • 50. Copyright © 2014 by John Wiley & Sons. All rights reserved. 50 Common Array Algorithm: Inserting an Element Figure 9 Inserting an Element in an Ordered Array
  • 51. Copyright © 2014 by John Wiley & Sons. All rights reserved. 51 Common Array Algorithm: Swapping Elements  To swap two elements, you need a temporary variable.  We need to save the first value in the temporary variable before replacing it. double temp = values[i]; values[i] = values[j];  Now we can set values[j] to the saved value. values[j] = temp;
  • 52. Copyright © 2014 by John Wiley & Sons. All rights reserved. 52 Common Array Algorithm: Swapping Elements Figure 10 Swapping Array Elements
  • 53. Copyright © 2014 by John Wiley & Sons. All rights reserved. 53 Common Array Algorithm: Copying an Array  Copying an array variable yields a second reference to the same array: double[] values = new double[6]; . . . // Fill array double[] prices = values;  To make a true copy of an array, call the Arrays.copyOf method: double[] prices = Arrays.copyOf(values, values.length);
  • 54. Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 Common Array Algorithm: Copying an Array Figure 11 Copying an Array Reference versus Copying an Array
  • 55. Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 Common Array Algorithm: Growing an Array  To grow an array that has run out of space, use the Arrays.copyOf method to double the length of an array double[] newValues = Arrays.copyOf(values, 2 * values.length); values = newValues;
  • 56. Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 Common Array Algorithm: Growing an Array Figure 12 Growing an Array
  • 57. Copyright © 2014 by John Wiley & Sons. All rights reserved. 57 Reading Input  To read a sequence of arbitrary length: • Add the inputs to an array until the end of the input has been reached. • Grow when needed. double[] inputs = new double[INITIAL_SIZE]; int currentSize = 0; while (in.hasNextDouble()) { // Grow the array if it has been completely filled if (currentSize >= inputs.length) { inputs = Arrays.copyOf(inputs, 2 * inputs.length); // Grow the inputs array } inputs[currentSize] = in.nextDouble(); currentSize++; } • Discard unfilled elements. inputs = Arrays.copyOf(inputs, currentSize);
  • 58. Copyright © 2014 by John Wiley & Sons. All rights reserved. 58 section_3/LargestInArray.java 1 import java.util.Scanner; 2 3 /** 4 This program reads a sequence of values and prints them, marking the largest value. 5 */ 6 public class LargestInArray 7 { 8 public static void main(String[] args) 9 { 10 final int LENGTH = 100; 11 double[] values = new double[LENGTH]; 12 int currentSize = 0; 13 14 // Read inputs 15 16 System.out.println("Please enter values, Q to quit:"); 17 Scanner in = new Scanner(System.in); 18 while (in.hasNextDouble() && currentSize < values.length) 19 { 20 values[currentSize] = in.nextDouble(); 21 currentSize++; 22 } 23 Continued
  • 59. Copyright © 2014 by John Wiley & Sons. All rights reserved. 59 section_3/LargestInArray.java 24 // Find the largest value 25 26 double largest = values[0]; 27 for (int i = 1; i < currentSize; i++) 28 { 29 if (values[i] > largest) 30 { 31 largest = values[i]; 32 } 33 } 34 35 // Print all values, marking the largest 36 37 for (int i = 0; i < currentSize; i++) 38 { 39 System.out.print(values[i]); 40 if (values[i] == largest) 41 { 42 System.out.print(" <== largest value"); 43 } 44 System.out.println(); 45 } 46 } 47 } Continued
  • 60. Copyright © 2014 by John Wiley & Sons. All rights reserved. 60 section_3/LargestInArray.java Program Run Please enter values, Q to quit: 34.5 80 115 44.5 Q 34.5 80 115 <== largest value 44.5
  • 61. Copyright © 2014 by John Wiley & Sons. All rights reserved. 61 Self Check 7.13 Answer: 20 <== largest value 10 20 <== largest value Given these inputs, what is the output of the LargestInArray program? 20 10 20 Q
  • 62. Copyright © 2014 by John Wiley & Sons. All rights reserved. 62 Self Check 7.14 Answer: int count = 0; for (double x : values) { if (x == 0) { count++; } } Write a loop that counts how many elements in an array are equal to zero.
  • 63. Copyright © 2014 by John Wiley & Sons. All rights reserved. 63 Self Check 7.15 Answer: If all elements of values are negative, then the result is incorrectly computed as 0. Consider the algorithm to find the largest element in an array. Why don’t we initialize largest and i with zero, like this? double largest = 0; for (int i = 0; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }
  • 64. Copyright © 2014 by John Wiley & Sons. All rights reserved. 64 Self Check 7.16 Answer: for (int i = 0; i < values.length; i++) { System.out.print(values[i]); if (i < values.length – 1) { System.out.print(" | "); } } Now you know why we set up the loop the other way. When printing separators, we skipped the separator before the initial element. Rewrite the loop so that the separator is printed after each element, except for the last element.
  • 65. Copyright © 2014 by John Wiley & Sons. All rights reserved. 65 Self Check 7.17 Answer: If the array has no elements, then the program terminates with an exception. What is wrong with these statements for printing an array with separators? System.out.print(values[0]); for (int i = 1; i < values.length; i++) { System.out.print(", " + values[i]); }
  • 66. Copyright © 2014 by John Wiley & Sons. All rights reserved. 66 Self Check 7.18 Answer: If there is a match, then pos is incremented before the loop exits. When finding the position of a match, we used a while loop, not a for loop. What is wrong with using this loop instead? for (pos = 0; pos < values.length && !found; pos++) { if (values[pos] > 100) { found = true; } }
  • 67. Copyright © 2014 by John Wiley & Sons. All rights reserved. 67 Self Check 7.19 Answer: This loop sets all elements to values[pos]. When inserting an element into an array, we moved the elements with larger index values, starting at the end of the array. Why is it wrong to start at the insertion location, like this? for (int i = pos; i < currentSize - 1; i++) { values[i + 1] = values[i]; }
  • 68. Copyright © 2014 by John Wiley & Sons. All rights reserved. 68 Problem Solving: Adapting Algorithms  By combining fundamental algorithms, you can solve complex programming tasks.  Problem: Compute the final quiz score by dropping the lowest and finding the sum of all the remaining scores.  Related algorithms: • Calculating the sum • Finding the minimum value • Removing an element
  • 69. Copyright © 2014 by John Wiley & Sons. All rights reserved. 69 Problem Solving: Adapting Algorithms  A plan of attack Find the minimum. Remove it from the array. Calculate the sum.  Try it out. The minimum is 4  We need to use a linear search to find the position of the minimum.
  • 70. Copyright © 2014 by John Wiley & Sons. All rights reserved. 70 Problem Solving: Adapting Algorithms  Revise the plan of attack Find the minimum value. Find its position. Remove that position from the array. Calculate the sum.  Try it out • Find the minimum value of 4. Linear search tells us that the value 4 occurs at position 5. • Remove it  Compute the sum: 8 + 7 + 8.5 + 9.5 + 7 + 10 = 50.  This walk-through demonstrates that our strategy works.
  • 71. Copyright © 2014 by John Wiley & Sons. All rights reserved. 71 Problem Solving: Adapting Algorithms  Inefficient to find the minimum and then make another pass through the array to obtain its position.  Modify minimum algorithm to remember the position of the smallest element int smallestPosition = 0; for (int i = 1; i < values.length; i++) { if (values[i] < values[smallestPosition]) { smallestPosition = I; } }  Final Strategy Find the position of the minimum. Remove it from the array. Calculate the sum.
  • 72. Copyright © 2014 by John Wiley & Sons. All rights reserved. 72 Self Check 7.20 Answer: Use the first algorithm. The order of elements does not matter when computing the sum. Section 7.3.6 has two algorithms for removing an element. Which of the two should be used to solve the task described in this section?
  • 73. Copyright © 2014 by John Wiley & Sons. All rights reserved. 73 Self Check 7.21  Answer: Find the minimum value. Calculate the sum. Subtract the minimum value. It isn’t actually necessary to remove the minimum in order to compute the total score. Describe an alternative.
  • 74. Copyright © 2014 by John Wiley & Sons. All rights reserved. 74 Self Check 7.22 Answer: Use the algorithm for counting matches (Section 6.7.2) twice, once for counting the positive values and once for counting the negative values. How can you print the number of positive and negative values in a given array, using one or more of the algorithms in Section 6.7?
  • 75. Copyright © 2014 by John Wiley & Sons. All rights reserved. 75 Self Check 7.23 Answer: You need to modify the algorithm in Section 7.3.4. boolean first = true; for (int i = 0; i < values.length; i++) { if (values[i] > 0)) { if (first) { first = false; } else { System.out.print(", "); } } System.out.print(values[i]); } Note that you can no longer use i > 0 as the criterion for printing a separator. How can you print all positive values in an array, separated by commas?
  • 76. Copyright © 2014 by John Wiley & Sons. All rights reserved. 76 Self Check 7.24 Answer: Use the algorithm to collect all positive elements in an array, then use the algorithm in Section 7.3.4 to print the array of matches. Consider the following algorithm for collecting all matches in an array: int matchesSize = 0; for (int i = 0; i < values.length; i++) { if (values[i] fulfills the condition) { matches[matchesSize] = values[i]; matchesSize++; } } How can this algorithm help you with Self Check 23?
  • 77. Copyright © 2014 by John Wiley & Sons. All rights reserved. 77 Problem Solving: Discovering Algorithms by Manipulating Physical Objects  Manipulating physical objects can give you ideas for discovering algorithms.  The Problem: You are given an array whose size is an even number, and you are to switch the first and the second half.  Example • This array • will become
  • 78. Copyright © 2014 by John Wiley & Sons. All rights reserved. 78 Problem Solving: Discovering Algorithms by Manipulating Physical Objects  Use a sequence of coins, playing cards, or toys to visualize an array of values.  Original line of coins  Removal of an array element  Insertion of an array element
  • 79. Copyright © 2014 by John Wiley & Sons. All rights reserved. 79 Problem Solving: Discovering Algorithms by Manipulating Physical Objects  Swapping array elements  Swap the coins in positions 0 and 4:
  • 80. Copyright © 2014 by John Wiley & Sons. All rights reserved. 80 Problem Solving: Discovering Algorithms by Manipulating Physical Objects  Swap the coins in positions 1 and 5:  Two more swaps
  • 81. Copyright © 2014 by John Wiley & Sons. All rights reserved. 81 Problem Solving: Discovering Algorithms by Manipulating Physical Objects  The pseudocode i = 0 j = size / 2 While (i < size / 2) Swap elements at positions i and j i++ j++
  • 82. Copyright © 2014 by John Wiley & Sons. All rights reserved. 82 Self Check 7.25 Answer: The paperclip for i assumes positions 0, 1, 2, 3. When i is incremented to 4, the condition i < size / 2 becomes false, and the loop ends. Similarly, the paperclip for j assumes positions 4, 5, 6, 7, which are the valid positions for the second half of the array. Walk through the algorithm that we developed in this section, using two paper clips to indicate the positions for i and j. Explain why there are no bounds errors in the pseudocode.
  • 83. Copyright © 2014 by John Wiley & Sons. All rights reserved. 83 Self Check 7.26 Answer: It reverses the elements in the array. Take out some coins and simulate the following pseudocode, using two paper clips to indicate the positions for i and j. i = 0 j = size – 1 While (i < j) Swap elements at positions i and j i++ j-- What does the algorithm do?
  • 84. Copyright © 2014 by John Wiley & Sons. All rights reserved. 84 Self Check 7.27 Consider the task of rearranging all elements in an array so that the even numbers come first. Otherwise, the order doesn’t matter. For example, the array 1 4 14 2 1 3 5 6 23 could be rearranged to 4 2 14 6 1 5 3 23 1 Using coins and paperclips, discover an algorithm that solves this task by swapping elements, then describe it in pseudocode. Continued
  • 85. Copyright © 2014 by John Wiley & Sons. All rights reserved. 85 Self Check 7.27 Answer: Here is one solution. The basic idea is to move all odd elements to the end. Put one paper clip at the beginning of the array and one at the end. If the element at the first paper clip is odd, swap it with the one at the other paper clip and move that paper clip to the left. Otherwise, move the first paper clip to the right. Stop when the two paper clips meet. Here is the pseudocode: i = 0 j = size – 1 While (i < j) If (a[i] is odd) Swap elements at positions i and j. j-- Else i++
  • 86. Copyright © 2014 by John Wiley & Sons. All rights reserved. 86 Self Check 7.28 Answer: Here is one solution. The idea is to remove all odd elements and move them to the end. The trick is to know when to stop. Nothing is gained by moving odd elements into the area that already contains moved elements, so we want to mark that area with another paper clip. i = 0 moved = size While (i < moved) If (a[i] is odd) Remove the element at position i and add it at the end. moved--  Discover an algorithm for the task of Self Check 27 that uses removal and insertion of elements instead of swapping.
  • 87. Copyright © 2014 by John Wiley & Sons. All rights reserved. 87 Self Check 7.29 Answer: When you read inputs, you get to see values one at a time, and you can’t peek ahead. Picking cards one at a time from a deck of cards simulates this process better than looking at a sequence of items, all of which are revealed. Consider the algorithm in Section 6.7.5 that finds the largest element in a sequence of inputs—not the largest element in an array. Why is this algorithm better visualized by picking playing cards from a deck rather than arranging toy soldiers in a sequence?
  • 88. Copyright © 2014 by John Wiley & Sons. All rights reserved. 88 Two-Dimensional Arrays  An arrangement consisting of rows and columns of values • Also called a matrix.  Example: medal counts of the figure skating competitions at the 2010 Winter Olympics. Figure 13 Figure Skating Medal counts
  • 89. Copyright © 2014 by John Wiley & Sons. All rights reserved. 89 Two-Dimensional Arrays  Use a two-dimensional array to store tabular data.  When constructing a two-dimensional array, specify how many rows and columns are needed: final int COUNTRIES = 7; final int MEDALS = 3; int[][] counts = new int[COUNTRIES][MEDALS];
  • 90. Copyright © 2014 by John Wiley & Sons. All rights reserved. 90 Two-Dimensional Arrays  You can declare and initialize the array by grouping each row: int[][] counts = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } };  You cannot change the size of a two-dimensional array once it has been declared.
  • 91. Copyright © 2014 by John Wiley & Sons. All rights reserved. 91 Syntax 7.3 Two-Dimensional Array Declaration
  • 92. Copyright © 2014 by John Wiley & Sons. All rights reserved. 92 Accessing Elements  Access by using two index values, array[i][j] int medalCount = counts[3][1];  Use nested loops to access all elements in a two-dimensional array.  Example: print all the elements of the counts array for (int i = 0; i < COUNTRIES; i++) { // Process the ith row for (int j = 0; j < MEDALS; j++) { // Process the jth column in the ith row System.out.printf("%8d", counts[i][j]); } System.out.println(); // Start a new line at the end of the row }
  • 93. Copyright © 2014 by John Wiley & Sons. All rights reserved. 93 Accessing Elements Figure 14 Accessing an Element in a Two-Dimensional Array
  • 94. Copyright © 2014 by John Wiley & Sons. All rights reserved. 94 Accessing Elements  Number of rows: counts.length  Number of columns: counts[0].length  Example: print all the elements of the counts array for (int i = 0; i < counts.length; i++) { for (int j = 0; j < counts[0].length; j++) { System.out.printf("%8d", counts[i][j]); } System.out.println(); }
  • 95. Copyright © 2014 by John Wiley & Sons. All rights reserved. 95 Locating Neighboring Elements Figure 15 Neighboring Locations in a Two-Dimensional Array  Watch out for elements at the boundary array • counts[0][1] does not have a neighbor to the top
  • 96. Copyright © 2014 by John Wiley & Sons. All rights reserved. 96 Accessing Rows and Columns  Problem: To find the number of medals won by a country • Find the sum of the elements in a row  To find the sum of the ith row • compute the sum of counts[i][j], where j ranges from 0 to MEDALS - 1.
  • 97. Copyright © 2014 by John Wiley & Sons. All rights reserved. 97 Accessing Rows and Columns  Loop to compute the sum of the ith row int total = 0; for (int j = 0; j < MEDALS; j++) { total = total + counts[i][j]; }
  • 98. Copyright © 2014 by John Wiley & Sons. All rights reserved. 98 Accessing Rows and Columns  To find the sum of the jth column • Form the sum of counts[i][j], where i ranges from 0 to COUNTRIES – 1 int total = 0; for (int i = 0; i < COUNTRIES; i++ { total = total + counts[i][j]; }
  • 99. Copyright © 2014 by John Wiley & Sons. All rights reserved. 99 section_6/Medals.java 1 /** 2 This program prints a table of medal winner counts with row totals. 3 */ 4 public class Medals 5 { 6 public static void main(String[] args) 7 { 8 final int COUNTRIES = 7; 9 final int MEDALS = 3; 10 11 String[] countries = 12 { 13 "Canada", 14 "China", 15 "Germany", 16 "Korea", 17 "Japan", 18 "Russia", 19 "United States" 20 }; 21 22 int[][] counts = 23 { 24 { 1, 0, 1 }, 25 { 1, 1, 0 }, 26 { 0, 0, 1 }, 27 { 1, 0, 0 }, 28 { 0, 1, 1 }, 29 { 0, 1, 1 }, 30 { 1, 1, 0 } 31 }; 32 Continued
  • 100. Copyright © 2014 by John Wiley & Sons. All rights reserved. 100 section_6/Medals.java 33 System.out.println(" Country Gold Silver Bronze Total"); 34 35 // Print countries, counts, and row totals 36 for (int i = 0; i < COUNTRIES; i++) 37 { 38 // Process the ith row 39 System.out.printf("%15s", countries[i]); 40 41 int total = 0; 42 43 // Print each row element and update the row total 44 for (int j = 0; j < MEDALS; j++) 45 { 46 System.out.printf("%8d", counts[i][j]); 47 total = total + counts[i][j]; 48 } 49 50 // Display the row total and print a new line 51 System.out.printf("%8dn", total); 52 } 53 } 54 } Continued
  • 101. Copyright © 2014 by John Wiley & Sons. All rights reserved. 101 section_6/Medals.java Program Run
  • 102. Copyright © 2014 by John Wiley & Sons. All rights reserved. 102 Self Check 7.30 Answer: You get the total number of gold, silver, and bronze medals in the competition. In our example, there are four of each. What results do you get if you total the columns in our sample data?
  • 103. Copyright © 2014 by John Wiley & Sons. All rights reserved. 103 Self Check 7.31 Consider an 8 × 8 array for a board game: int[][] board = new int[8][8]; Using two nested loops, initialize the board so that zeros and ones alternate, as on a checkerboard: 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 . . . 1 0 1 0 1 0 1 0 Hint: Check whether i + j is even. Continued
  • 104. Copyright © 2014 by John Wiley & Sons. All rights reserved. 104 Self Check 7.31 Answer: for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { board[i][j] = (i + j) % 2; } }
  • 105. Copyright © 2014 by John Wiley & Sons. All rights reserved. 105 Self Check 7.32 Answer: String[][] board = new String[3][3]; Declare a two-dimensional array for representing a tic-tac-toe board. The board has three rows and columns and contains strings "x", "o", and " ".
  • 106. Copyright © 2014 by John Wiley & Sons. All rights reserved. 106 Self Check 7.33 Answer: board[0][2] = "x"; Write an assignment statement to place an "x" in the upper-right corner of the tic-tac-toe board in Self Check 32.
  • 107. Copyright © 2014 by John Wiley & Sons. All rights reserved. 107 Self Check 7.34 Answer: board[0][0], board[1][1], board[2][2] Which elements are on the diagonal joining the upper-left and the lower-right corners of the tic-tac-toe board in Self Check 32?
  • 108. Copyright © 2014 by John Wiley & Sons. All rights reserved. 108 Array Lists  An array list stores a sequence of values whose size can change.  An array list can grow and shrink as needed.  ArrayList class supplies methods for many common tasks, such as inserting and removing elements.  An array list expands to hold as many elements as needed.
  • 109. Copyright © 2014 by John Wiley & Sons. All rights reserved. 109 Syntax 7.4 Array Lists
  • 110. Copyright © 2014 by John Wiley & Sons. All rights reserved. 110 Declaring and Using Array Lists  To declare an array list of strings ArrayList<String> names = new ArrayList<String>();  To use an array list import java.util.ArrayList;  ArrayList is a generic class  Angle brackets denote a type parameter • Replace String with any other class to get a different array list type
  • 111. Copyright © 2014 by John Wiley & Sons. All rights reserved. 111 Declaring and Using Array Lists  ArrayList<String> is first constructed, it has size 0  Use the add method to add an object to the end of the array list: names.add("Emily"); // Now names has size 1 and element "Emily” names.add("Bob"); // Now names has size 2 and elements "Emily", "Bob” names.add("Cindy"); // names has size 3 and elements "Emily", "Bob", // and "Cindy”  The size method gives the current size of the array list. • Size is now 3 Figure 17 Adding an Array List Element with add
  • 112. Copyright © 2014 by John Wiley & Sons. All rights reserved. 112 Declaring and Using Array Lists  To obtain an array list element, use the get method • Index starts at 0  To retrieve the name with index 2: String name = names.get(2); // Gets the third element // of the array list  The last valid index is names.size() - 1 • A common bounds error: int i = names.size(); name = names.get(i); // Error  To set an array list element to a new value, use the set method: names.set(2, "Carolyn");
  • 113. Copyright © 2014 by John Wiley & Sons. All rights reserved. 113 Declaring and Using Array Lists  An array list has methods for adding and removing elements in the middle.  This statement adds a new element at position 1 and moves all elements with index 1 or larger by one position. names.add(1, "Ann");
  • 114. Copyright © 2014 by John Wiley & Sons. All rights reserved. 114 Declaring and Using Array Lists  The remove method, • removes the element at a given position • moves all elements after the removed element down by one position • and reduces the size of the array list by 1. names.remove(1);  To print an array list: System.out.println(names); // Prints [Emily, Bob, Carolyn]
  • 115. Copyright © 2014 by John Wiley & Sons. All rights reserved. 115 Declaring and Using Array Lists Figure 18 Adding and Removing Elements in the Middle of an Array List
  • 116. Copyright © 2014 by John Wiley & Sons. All rights reserved. 116 Using the Enhanced for Loop with Array Lists  You can use the enhanced for loop to visit all the elements of an array list ArrayList<String> names = . . . ; for (String name : names) { System.out.println(name); }  This is equivalent to: for (int i = 0; i < names.size(); i++) { String name = names.get(i); System.out.println(name); }
  • 117. Copyright © 2014 by John Wiley & Sons. All rights reserved. 117 Copying Array Lists  Copying an array list reference yields two references to the same array list.  After the code below is executed • Both names and friends reference the same array list to which the string "Harry" was added. ArrayList<String> friends = names; friends.add("Harry"); Figure 19 Copying an Array List Reference
  • 118. Copyright © 2014 by John Wiley & Sons. All rights reserved. 118 Copying Array Lists  To make a copy of an array list, construct the copy and pass the original list into the constructor: ArrayList<String> newNames = new ArrayList<String>(names);
  • 119. Copyright © 2014 by John Wiley & Sons. All rights reserved. 119 Working With Array Lists
  • 120. Copyright © 2014 by John Wiley & Sons. All rights reserved. 120 Wrapper Classes  You cannot directly insert primitive type values into array lists.  Like truffles that must be in a wrapper to be sold, a number must be placed in a wrapper to be stored in an array list.  Use the matching wrapper class.
  • 121. Copyright © 2014 by John Wiley & Sons. All rights reserved. 121 Wrapper Classes  To collect double values in an array list, you use an ArrayList<Double>.  If you assign a double value to a Double variable, the number is automatically “put into a box”  Called auto-boxing: • Automatic conversion between primitive types and the corresponding wrapper classes: Double wrapper = 29.95; • Wrapper values are automatically “unboxed” to primitive types double x = wrapper; Figure 20 A Wrapper Class Variable
  • 122. Copyright © 2014 by John Wiley & Sons. All rights reserved. 122 Using Array Algorithms with Array Lists  The array algorithms can be converted to array lists simply by using the array list methods instead of the array syntax.  Code to find the largest element in an array: double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }  Code to find the largest element in an array list: double largest = values.get(0); for (int i = 1; i < values.size(); i++) { if (values.get(i) > largest) { largest = values.get(i); } }
  • 123. Copyright © 2014 by John Wiley & Sons. All rights reserved. 123 Storing Input Values in an Array List  To collect an unknown number of inputs, array lists are much easier to use than arrays.  Simply read the inputs and add them to an array list: ArrayList<Double> inputs = new ArrayList<Double>(); while (in.hasNextDouble()) { inputs.add(in.nextDouble()); }
  • 124. Copyright © 2014 by John Wiley & Sons. All rights reserved. 124 Removing Matches  To remove elements from an array list, call the remove method.  Error: skips the element after the moved element ArrayList<String> words = ...; for (int i = 0; i < words.size(); i++) { String word = words.get(i); if (word.length() < 4) { Remove the element at index i. } }  Concrete example
  • 125. Copyright © 2014 by John Wiley & Sons. All rights reserved. 125 Removing Matches  Should not increment i when an element is removed  Pseudocode If the element at index i matches the condition Remove the element. Else Increment i.
  • 126. Copyright © 2014 by John Wiley & Sons. All rights reserved. 126 Removing Matches  Use a while loop, not a for loop int i = 0; while (i < words.size()) { String word = words.get(i); if (word.length() < 4) { words.remove(i); } else { i++; } }
  • 127. Copyright © 2014 by John Wiley & Sons. All rights reserved. 127 Choosing Between Array Lists and Arrays  For most programming tasks, array lists are easier to use than arrays • Array lists can grow and shrink. • Arrays have a nicer syntax.  Recommendations • If the size of a collection never changes, use an array. • If you collect a long sequence of primitive type values and you are concerned about efficiency, use an array. • Otherwise, use an array list.
  • 128. Copyright © 2014 by John Wiley & Sons. All rights reserved. 128 Choosing Between Array Lists and Arrays
  • 129. Copyright © 2014 by John Wiley & Sons. All rights reserved. 129 section_7/LargestInArrayList.java 1 import java.util.ArrayList; 2 import java.util.Scanner; 3 4 /** 5 This program reads a sequence of values and prints them, marking the largest value. 6 */ 7 public class LargestInArrayList 8 { 9 public static void main(String[] args) 10 { 11 ArrayList<Double> values = new ArrayList<Double>(); 12 13 // Read inputs 14 15 System.out.println("Please enter values, Q to quit:"); 16 Scanner in = new Scanner(System.in); 17 while (in.hasNextDouble()) 18 { 19 values.add(in.nextDouble()); 20 } 21 Continued
  • 130. Copyright © 2014 by John Wiley & Sons. All rights reserved. 130 section_7/LargestInArrayList.java 22 // Find the largest value 23 24 double largest = values.get(0); 25 for (int i = 1; i < values.size(); i++) 26 { 27 if (values.get(i) > largest) 28 { 29 largest = values.get(i); 30 } 31 } 32 33 // Print all values, marking the largest 34 35 for (double element : values) 36 { 37 System.out.print(element); 38 if (element == largest) 39 { 40 System.out.print(" <== largest value"); 41 } 42 System.out.println(); 43 } 44 } 45 } Continued
  • 131. Copyright © 2014 by John Wiley & Sons. All rights reserved. 131 section_7/LargestInArrayList.java Program Run Please enter values, Q to quit: 35 80 115 44.5 Q 35 80 115 <== largest value 44.5
  • 132. Copyright © 2014 by John Wiley & Sons. All rights reserved. 132 Self Check 7.35 Answer: ArrayList<Integer> primes = new ArrayList<Integer>(); primes.add(2); primes.add(3); primes.add(5); primes.add(7); primes.add(11); Declare an array list primes of integers that contains the first five prime numbers (2, 3, 5, 7, and 11).
  • 133. Copyright © 2014 by John Wiley & Sons. All rights reserved. 133 Self Check 7.36 Answer: for (int i = primes.size() - 1; i >= 0; i--) { System.out.println(primes.get(i)); } Given the array list primes declared in Self Check 35, write a loop to print its elements in reverse order, starting with the last element.
  • 134. Copyright © 2014 by John Wiley & Sons. All rights reserved. 134 Self Check 7.37 Answer: "Ann", "Cal" What does the array list names contain after the following statements? ArrayList<String> names = new ArrayList<String>; names.add("Bob"); names.add(0, "Ann"); names.remove(1); names.add("Cal");
  • 135. Copyright © 2014 by John Wiley & Sons. All rights reserved. 135 Self Check 7.38 Answer: The names variable has not been initialized. What is wrong with this code snippet? ArrayList<String> names; names.add(Bob);
  • 136. Copyright © 2014 by John Wiley & Sons. All rights reserved. 136 Self Check 7.39 Consider this method that appends the elements of one array list to another: public void append(ArrayList<String> target, ArrayList<String> source) { for (int i = 0; i < source.size(); i++) { target.add(source.get(i)); } } What are the contents of names1 and names2 after these statements? ArrayList<String> names1 = new ArrayList<String>(); names1.add("Emily"); names1.add("Bob"); names1.add("Cindy"); ArrayList<String> names2 = new ArrayList<String>(); names2.add("Dave"); append(names1, names2); Continued
  • 137. Copyright © 2014 by John Wiley & Sons. All rights reserved. 137 Self Check 7.39 Answer: names1 contains "Emily", "Bob", "Cindy", "Dave"; names2 contains "Dave"
  • 138. Copyright © 2014 by John Wiley & Sons. All rights reserved. 138 Self Check 7.40 Answer: Because the number of weekdays doesn’t change, there is no disadvantage to using an array, and it is easier to initialize: String[] weekdayNames = { "Monday", "Tuesday", "Wednesday", "Thursday", “Friday”, "Saturday", "Sunday" }; Suppose you want to store the names of the weekdays. Should you use an array list or an array of seven strings?
  • 139. Copyright © 2014 by John Wiley & Sons. All rights reserved. 139 Self Check 7.41 Answer: Reading inputs into an array list is much easier. The ch07/section_7 directory of your source code contains an alternate implementation of the problem solution in How To 7.1 on page 334. Compare the array and array list implementations. What is the primary advantage of the latter?
  • 140. Copyright © 2014 by John Wiley & Sons. All rights reserved. 140 Regression Testing  Test suite: a set of tests for repeated testing  Cycling: bug that is fixed but reappears in later versions  Regression testing: involves repeating previously run tests to ensure that known failures of prior versions do not appear in new versions
  • 141. Copyright © 2014 by John Wiley & Sons. All rights reserved. 141 Regression Testing – Two Approaches  Organize a suite of test with multiple tester classes: ScoreTester1, ScoreTester2, … public class ScoreTester1 { public static void main(String[] args) { Student fred = new Student(100); fred.addScore(10); fred.addScore(20); fred.addScore(5); System.out.println("Final score: " + fred.finalScore()); System.out.println("Expected: 30"); } }  Provide a generic tester, and feed it inputs from multiple files.
  • 142. Copyright © 2014 by John Wiley & Sons. All rights reserved. 142 section_8/ScoreTester.java generic tester 1 import java.util.Scanner; 2 3 public class ScoreTester 4 { 5 public static void main(String[] args) 6 { 7 Scanner in = new Scanner(System.in); 8 double expected = in.nextDouble(); 9 Student fred = new Student(100); 10 while (in.hasNextDouble()) 11 { 12 if (!fred.addScore(in.nextDouble())) 13 { 14 System.out.println("Too many scores."); 15 return; 16 } 17 } 18 System.out.println("Final score: " + fred.finalScore()); 19 System.out.println("Expected: " + expected); 20 } 21 }
  • 143. Copyright © 2014 by John Wiley & Sons. All rights reserved. 143 Input and Output Redirection  Section_8/input1.txt contains: 30 10 20 5  Type the following command into a shell window • Input redirection java ScoreTester < input1.txt  Program Run: Final score: 30 Expected: 30  Output redirection: java ScoreTester < input1.txt > output1.txt
  • 144. Copyright © 2014 by John Wiley & Sons. All rights reserved. 144 Self Check 7.42 Answer: It is possible to introduce errors when modifying code. Suppose you modified the code for a method. Why do you want to repeat tests that already passed with the previous version of the code?
  • 145. Copyright © 2014 by John Wiley & Sons. All rights reserved. 145 Self Check 7.43 Answer: Add a test case to the test suite that verifies that the error is fixed. Suppose a customer of your program finds an error. What action should you take beyond fixing the error?
  • 146. Copyright © 2014 by John Wiley & Sons. All rights reserved. 146 Self Check 7.44 Answer: There is no human user who would see the prompts because input is provided from a file. Why doesn't the ScoreTester program contain prompts for the inputs?