Show
Chapter 7 – Arrays and Array ListsChapter Goals
Arrays
Arrays
System.out.println(values[4]); ArraysFigure 1 An Array of Size 10 Syntax 7.1 ArraysArrays
Arrays - Bounds Error
Declaring ArraysArray References
Figure 2 Two Array Variables Referencing the Same Array Using Arrays with Methods
Partially Filled Arrays
Partially Filled Arrays
Partially Filled Arrays
Partially Filled Arrays
Self Check 7.1Declare an array of integers containing the first five prime numbers
Self Check 7.2Assume the array primeshas 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]; }
Self Check 7.3Assume the array primeshas 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]++; }
Self Check 7.4Given 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.
Self Check 7.5Declare an array called wordsthat can hold ten elements of type String.
Self Check 7.6Declare an array containing two strings, "Yes", and "No".
Self Check 7.7Can 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?
Self Check 7.8Declare a method of a class Lotterythat returns a combination of nnumbers. You don’t need to implement the method.
Make Parallel Arrays into Arrays of Objects
Figure 4 Make Parallel Arrays into Arrays of ObjectsAvoid parallel arrays by changing them into arrays of objects: BankAccount[] accounts; Figure 5 The Enhanced for Loop
The Enhanced for Loop
Syntax 7.2 The Enhanced for LoopSelf Check 7.9What does this enhanced forloop do? int counter = 0; for (double element : values) { if (element == 0) { counter++; } }
Self Check 7.10Write an enhanced forloop that prints all elements in the array values.
Self Check 7.11Write an enhanced forloop that multiplies all elements in a double[]array named factors, accumulating the result in a variable named product.
Self Check 7.12Why is the enhanced forloop not an appropriate shortcut for the following basic forloop? for (int i = 0; i < values.length; i++) { values[i] = i * i; }
Common Array Algorithm: Filling
Common Array Algorithm: Sum and Average
Common Array Algorithm: Maximum or Minimum
Common Array Algorithm: Element Separators
Common Array Algorithm: Linear Search
Common Array Algorithm: Linear Search
Common Array Algorithm: Removing an ElementProblem: To remove the element with index posfrom the array valueswith number of elements currentSize.
Figure 6 Removing an Element in an Unordered Array Common Array Algorithm: Removing an Element
Figure 7 Removing an Element in an Ordered Array Common Array Algorithm: Inserting an Element
Figure 8 Inserting an Element in an Unordered Array Common Array Algorithm: Inserting an Element
Figure 9 Inserting an Element in an Ordered Array Common Array Algorithm: Swapping Elements
Common Array Algorithm: Swapping ElementsFigure 10 Swapping Array Elements Common Array Algorithm: Copying an ArrayCommon Array Algorithm: Growing an ArrayReading Input
inputs = Arrays.copyOf(inputs, currentSize); section_3/LargestInArray.javaProgram Run:
Self Check 7.13Given these inputs, what is the output of the LargestInArrayprogram? 20 10 20 Q
Self Check 7.14Write a loop that counts how many elements in an array are equal to zero.
Self Check 7.15Consider 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]; } }
Self Check 7.16When 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.
Self Check 7.17What 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]); }
Self Check 7.18When finding the position of a match, we used a whileloop, not a forloop. What is wrong with using this loop instead? for (pos = 0; pos < values.length && !found; pos++) { if (values[pos] > 100) { found = true; } }
Self Check 7.19When 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]; }
Problem Solving: Adapting Algorithms
Problem Solving: Adapting Algorithms - continued
Problem Solving: Adapting Algorithms - continued
Self Check 7.20Section 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?
Self Check 7.21It isn’t actually necessary to remove the minimum in order to compute the total score. Describe an alternative.
Self Check 7.22How 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?
Self Check 7.23How can you print all positive values in an array, separated by commas?
Self Check 7.24Consider 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?
Problem Solving: Discovering Algorithms by Manipulating Physical Objects
Problem Solving: Discovering Algorithms by Manipulating Physical ObjectsProblem Solving: Discovering Algorithms by Manipulating Physical ObjectsProblem Solving: Discovering Algorithms by Manipulating Physical Objects
Self Check 7.25Walk 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.
Self Check 7.26Take 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?
Self Check 7.27Consider 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.
Self Check 7.28Discover an algorithm for the task of Self Check 27 that uses removal and insertion of elements instead of swapping.
Self Check 7.29Consider 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?
Two-Dimensional Arrays
Figure 13 Figure Skating Medal counts Two-Dimensional Arrays
Syntax 7.3 Two-Dimensional Array DeclarationAccessing Elements
Figure 14 Accessing an Element in a Two-Dimensional Array Accessing Elements
Locating Neighboring Elements
Figure 15 Neighboring Locations in a Two-Dimensional Array Accessing Rows and Columns
Accessing Rows and Columns
section_6/Medals.javaProgram Run:
Self Check 7.30What results do you get if you total the columns in our sample data?
Self Check 7.31Consider 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 0 1 0 1 0 1 0 1 Hint: Check whether i + j is even.
Self Check 7.32Declare a two-dimensional array for representing a tic-tac-toe board. The board has three rows and columns and contains strings "x", "o", and " ".
Self Check 7.33Write an assignment statement to place an "x"in the upper-right corner of the tic-tac-toe board in Self Check 32.
Self Check 7.34Which elements are on the diagonal joining the upper-left and the lower-right corners of the tic-tac-toe board in Self Check 32?
Array Lists
Syntax 7.4 Array ListsDeclaring and Using Array Lists
Declaring and Using Array Lists
Figure 17 Adding an Array List Element with add Declaring and Using Array Lists
names.set(2, "Carolyn"); Declaring and Using Array Lists
System.out.println(names); // Prints [Emily, Bob, Carolyn] Declaring and Using Array ListsFigure 18 Adding and Removing Elements in the Middle of an Array List Using the Enhanced for Loop with Array Lists
Copying Array Lists
Figure 19 Copying an Array List Reference ArrayList<String> newNames = new ArrayList<String>(names); Working with Array Lists
Wrapper ClassesWrapper Classes
double x = wrapper; Figure 20 A Wrapper Class Variable Using Array Algorithms with Array Lists
Storing Input Values in an Array List
Removing Matches
Removing Matches
Choosing Between Array Lists and Arrays
Choosing Between Array Lists and Arrayssection_7/LargestInArrayList.javaProgram Run:
Self Check 7.35Declare an array list primesof integers that contains the first five prime numbers (2, 3, 5, 7, and 11).
Self Check 7.36Given the array list primes declared in Self Check 35, write a loop to print its elements in reverse order, starting with the last element.
Self Check 7.37What 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");
Self Check 7.38What is wrong with this code snippet? ArrayList<String> names; names.add(Bob);
Self Check 7.39Consider 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 names1and names2after 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);
Self Check 7.40Suppose you want to store the names of the weekdays. Should you use an array list or an array of seven strings?
Self Check 7.41The ch07/section_7directory 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?
Regression Testing
Regression Testing - Two Approaches
Input and Output RedirectionSection_8/input1.txt30 10 20 5
java ScoreTester < input1.txt Final score: 30 Expected: 30 java ScoreTester < input1.txt > output1.txt Self Check 7.42Suppose you modified the code for a method. Why do you want to repeat tests that already passed with the previous version of the code?
Self Check 7.43Suppose a customer of your program finds an error. What action should you take beyond fixing the error?
Self Check 7.44Why doesn't the ScoreTesterprogram contain prompts for the inputs?
Which code snippet prints out the elements in a partially filled array of integers assuming currentSize?Which code snippet prints out the elements in a partially filled array of integers, assuming currentSize is the companion variable indicating the actual number of elements in the array? System. out. print(myArray[i]);
Which code will define the size of an array?With the help of the length variable, we can obtain the size of the array. Examples: int size = arr[]. length; // length can be used // for int[], double[], String[] // to know the length of the arrays.
When the order of elements is unimportant what is the most efficient way to remove an element from an array?When the order of the elements is unimportant, what is the most efficient way to remove an element from an array? Replace the element to be deleted with the last element in the array. the number of inputs may not be known in advance. Which one of the following statements is correct about the given code snippet?
What is the valid range of index values for an array of size 10?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.
|