Chapter 7 Review Exercise Solutions
R7.1
An index is an integer value which represents a position in an array or array list.
The bounds are the lowest and highest legal index value; that is, 0 and one less than the length of the array/size of the array list.
A bounds error occurs when an array or array list is accessed at an index that is outside the bounds.
R7.2
public class ExR7_2
{  
   public static void main(String[] args)
   { 
      String[] greeting = new String[2];
      greeting[0] = "Hello,";
      greeting[1] = "cruel";
      greeting[2] = "World!";
   }
} 
When you run this program, you get an array index out of bounds exception. 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
	at ExR7_2.main(ExR7_2.java:8)

The line number (8 in the example) helps you locate the error. 
R7.3
import java.util.ArrayList;

public class ExR7_3
{
   public static void main(String[] args)
   {
      ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
      accounts.add(new BankAccount(1,1500));
      accounts.add(new BankAccount(2,2500));
      accounts.add(new BankAccount(3,1000));
      accounts.add(new BankAccount(4, 500));
      
      BankAccount max = accounts.get(0);
      BankAccount min = accounts.get(0);
      for (BankAccount a : accounts)
      {
         if (a.getBalance() > max.getBalance())
            max = a;
            
         if (a.getBalance() < min.getBalance())
            min = a;
      }
      
      System.out.println(max.getAccountNumber() + " " 
            + max.getBalance());
      System.out.println(min.getAccountNumber() + " " 
            + min.getBalance());
   }
}
R7.4
import java.util.Scanner;
import java.util.ArrayList;
/**
   Reads 10 strings and inserts them into an array list. Then, 
   prints out the strings in the opposite order from which they 
   were entered.
 */
public class ExR7_4
{    
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        ArrayList<String> strings = new ArrayList<String>();
        System.out.println(
              "Enter ten strings, each ended by a newline.");
        
        for (int i = 0; i < 10; i++)
            strings.add(in.nextLine());
        
        for (int i = strings.size() - 1; i >= 0; i--)
            System.out.println(strings.get(i));
    }    
}
R7.5
for (BankAccount a : accounts)
{
   if (largestYet == null)
      largestYet = a;
   else
      if (a.getBalance() > largestYet.getBalance())
         largestYet = a;
}
return largestYet;

This approach is less efficient because we perform a check at every iteration (largestYet==null), even though we know that check is only going to be true on the first iteration of the loop. 
R7.6
The maximum value in the list could be smaller than 0 (i.e. negative). Then, the program would incorrectly set max to 0. We can fix the error by applying the same approach as in the function that finds the largest value in a list (as detailed in the book). Using this approach, we set max to be the first element of the list, and then iterate through the remaining elements, updating max if needed.
R7.7
a.	1 2 3 4 5 6 7 8 9 10 
for (int i = 0; i < 10 ; i++ )
   a[i] = i + 1; 
b.	0 2 4 6 8 10 12 14 16 18 20 
for (int i = 0; i <= 10 ; i++ )
   a[i] = 2 * i; 
c.	1 4 9 16 25 36 49 64 81 100 
for (int i = 0; i < 10 ; i++ )
   a[i] = (i + 1) * (i + 1); 
d.	0 0 0 0 0 0 0 0 0 0 
int[] a = new int[10];
e.	1 4 9 16 9 7 4 9 11 
int[] a = { 1, 4, 9, 16, 9, 7, 4, 9, 11 };
R7.8
The following code segment fills an array with ten random numbers, with possible repetitions.
int[] a = new int[10];
Random generator = new Random();
for (int i = 0; i < a.length; i++)
   a[i] = 1 + generator.nextInt(100);

The following code segment fills an array with ten different random numbers.
int[] a = new int[10];
Random generator = new Random();

int i = 0;
while (i < a.length)
{
   boolean found = false;
   int r = 1 + generator.nextInt(100);
   int j = 0;
   // Check if generated number "r" already exists in "a"
   while (!found && j < i)
   {
      if (a[j] == r)
         found = true;
      else
         j++;
   }
   // If "r" is a new number, store it in "a"
   if (!found)
   {
      a[i] = r;
      i++;
   }
}

Here is another approach that avoids repeated guesses:
int[] a = new int[10];
Random generator = new Random();

int[] values = new int[100];
for (int i = 0; i < 100; i++)
   values[i] = i + 1;

for (int i = 0; i < 10; i++)
{
   int r = generator.nextInt(100 - i);
   a[i] = values[r];
   values[r] = values[100 - i - 1];
}
R7.9
There is a bounds error. The index of the for loop begins at 1 -- skipping the first element of the array -- and ends with 10 -- which is one past the end and a fatal error. 
One remedy is to adjust the bounds for i:
for (int i = 0; i < 10; i++) values[i] = (i + 1) * (i + 1);
Another remedy is to adjust the array index:
for (int i = 1; i <= 10; i++) values [i - 1] = i * i;
R7.10
public class ArrayDebugDemo
{
   public static void main(String[] args)
   {
      int[]values = new int[20];

      for (int i = 0; i < 10; i++)
         values[i] = (i + 1) * (i + 1);
   }
}

The elements of the array beyond those that were filled are all zero. When i is 2, the array has been filled with ten numbers, and its content is 1, 4, 9, 0, 0, 0, ..., 0.
R7.11
/* a. */
for (int i = 0; i < values.length;  i++)
   sum = sum + values[i];

/* b. */
for (int i = 0; i < values.length; i++)
   if (values[i] == target)
      return true;

/* c. */
for (int i = 0; i < values.length; i++)
   values[i] = 2 * values[i];
R7.12
/* a. */
for (double element : values)
   sum = sum + element;

/* b. */
boolean isFirst = true;
for (double element : values)
{
   if (isFirst)
      isFirst = false;
   else
      sum = sum + element;
}

/* c. */
int i = 0;
for (double element : values)
{
   if (element == target)
      return i;
   i++;
}
R7.13
If no items have been added to the ArrayList, the first statement (System.out.print(values.get(0));) will cause an IndexOutOfBoundsException error.
R7.14
This for loop will continue through the entire array, even after an element larger than 100 is located. This is unnecessary processing and more important, the element identified will be the last element in the array that matches the criteria, not the first one, as specified.

R7.15
Array elements from i + 1 to the end of the array will all be overwritten the value of values[i] rather than moving their values to a larger index. 
R7.16
Each time you need another element in the array, you copy the entire array to a new location. This is very time consuming. Doubling the size of an array with ‘n’ elements means you will avoid copying n + (n + 1) + (n + 2) + … + (2n) elements before you need to increase the size of the array again, if it is necessary. 
R7.17
Parallel arrays are two or more arrays of equivalent length in which corresponding elements are logically related.
Parallel arrays are indications of poor programming because items that are conceptually related are not represented together. This makes it more difficult to change the data representation.
To avoid parallel arrays, find a concept that describes the related elements and make it into a class having instance variables corresponding to the separate array elements. Then, make a single array of the new class type.
R7.18
All elements of an array are of the same type.	true, but that type can be Object, "the lowest common denominator" of all Java classes	
An array index must be an integer.	true	
Arrays cannot contain string references as elements.	false, for example main(String[] args)	
Arrays cannot contain null references as elements.	false, when an array is first created, if it is an array of object references, all values are initialized with null	
Parallel arrays must have equal length.	true (in order to be parallel)	
Two-dimensional arrays always have the same number of rows as columns.	false (square matrices, however do)	
Two parallel arrays can be replaced by a two-dimensional array	false (the array elements might be of different type)	
Elements of different columns in a two-dimensional array can have different types.	false	
R7.19
•	Regression testing: Regression testing involves repeating previously run tests to ensure that known failures of prior versions do not appear in new versions of the software.
•	Test suite: A test suite is a set of tests for repeated testing..
R7.20
Cycling is a problem that occurs when a bug that is fixed appears again in a future version. To avoid cycling, it is always best to think through what really causes a bug and fix the root cause instead of doing a sequence of "Band-Aid" solutions. Also, you should perform regression testing to ensure that known failures of prior versions do not appear in new versions of the software.