new double[10]
double[] values;
double[] values = new double[10];
double[] moreValues = { 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 };
values[4] = 35;
System.out.println(values[4]);
Figure 1 An Array of Size 10
double[] values = new double[10];
double[] values = new double[10]; values[10] = value; // Error
int[] scores = { 10, 9, 7, 4, 5 }; int[] values = scores; // Copying array reference
scores[3] = 10; System.out.println(values[3]); // Prints 10
Figure 2 Two Array Variables Referencing the Same Array
public void addScores(int[] values) { for (int i = 0; i < values.length; i++) { totalScore = totalScore + values[i]; } }
int[] scores = { 10, 9, 7, 10 }; fred.addScores(scores);
public int[] getScores()
final int LENGTH = 100; double[] values = new double[LENGTH];
int currentSize = 0; Scanner in = new Scanner(System.in); while (in.hasNextDouble()) { if (currentSize < values.length) { values[currentSize] = in.nextDouble(); currentSize++; } }
for (int i = 0; i < currentSize; i++)
{
System.out.println(values[i]);
}
int[] primes = { 2, 3, 5, 7, 11 };
for (int i = 0; i < 2; i++) { primes[4 - i] = primes[i]; }
for (int i = 0; i < 5; i++) { primes[i]++; }
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.
values[0] = 10; values[9] = 10; or better: values[values.length - 1] = 10;
public class Lottery { public int[] getCombination(int n) { . . . } . . . }
int[] accountNumbers; double[] balances;
Figure 4
BankAccount[] accounts;
Figure 5
double[] values = . . .; double total = 0; for (double element : values) { total = total + element; }
for each element in values.
for (int i = 0; i < values.length; i++) { double element = values[i]; total = total + element; }
for (double element : values)
{
element = 0; // ERROR: this assignment does not modify array elements
}
for (int i = 0; i < values.length; i++) { values[i] = 0; // OK }
forLoop
int counter = 0; for (double element : values) { if (element == 0) { counter++; } }
for (double x : values) { System.out.println(x); }
double product = 1; for (double f : factors) { product = product * f; }
for (int i = 0; i < values.length; i++) { values[i] = i * i; }
for (int i = 0; i < values.length; i++) { values[i] = i * i; }
double total = 0; for (double element : values) { total = total + element; }
double average = 0; if (values.length > 0) { average = total / values.length; }
double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }
Ann | Bob | Cindy
for (int i = 0; i < names.size(); i++) { if (i > 0) { System.out.print(" | "); } System.out.print(names.value[i]); }
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"); }
values[pos] = values[currentSize - 1]; currentSize--;
Figure 6 Removing an Element in an Unordered Array
for (int i = pos + 1; i < currentSize; i++) { values[i - 1] = values[i]; } currentSize--;
Figure 7 Removing an Element in an Ordered Array
if (currentSize < values.length) { currentSize++ values[currentSize -1 ] = newElement; ; }
Figure 8 Inserting an Element in an Unordered Array
if (currentSize < values.length) { currentSize++; for (int i = currentSize - 1; i > pos; i--) { values[i] = values[i - 1]; } values[pos] = newElement; }
Figure 9 Inserting an Element in an Ordered Array
double temp = values[i]; values[i] = values[j];
values[j] = temp;
Figure 10 Swapping Array Elements
double[] values = new double[6];
. . . // Fill array
double[] prices = values;
double[] prices = Arrays.copyOf(values, values.length);
Figure 11 Copying an Array Reference versus Copying an Array
import java.util.Arrays;
double[] newValues = Arrays.copyOf(values, 2 * values.length);
values = newValues;);
Figure 12 Growing an Array
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++; }
inputs = Arrays.copyOf(inputs, currentSize);
Please enter values, Q to quit: 34.5 80 115 44.5 Q 34.5 80 115 <== largest value 44.5
20 <== largest value 10 20 <== largest value
int count = 0; for (double x : values) { if (x == 0) { count++; } }
double largest = 0; for (int i = 0; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }
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.
System.out.print(values[0]); for (int i = 1; i < values.length; i++) { System.out.print(", " + values[i]); }
for (pos = 0; pos < values.length && !found; pos++) { if (values[pos] > 100) { found = true; } }
for (int i = pos; i < currentSize - 1; i++) { values[i + 1] = values[i]; }
Find the minimum.
Remove it from the array.
Calculate the sum.
Find the minimum value. Find its position. Remove that position from the array. Calculate the sum.
int smallestPosition = 0; for (int i = 1; i < values.length; i++) { if (values[i] < values[smallestPosition]) { smallestPosition = i; } }
Find the position of the minimum. Remove it from the array. Calculate the sum.
Find the minimum value.
Calculate the sum.
Subtract the minimum value.
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.
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?
i = 0 j = size / 2 While (i < size / 2) Swap elements at positions i and j i++ j++
i = 0 j = size - 1 While (i < j) Swap elements at positions i and j i++ j--What does the algorithm do?
1 4 14 2 1 3 5 6 23
could be rearranged to4 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.i = 0 j = size - 1 While (i < j) If (a[i] is odd) Swap elements at positions i and j. j-- Else i++
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--
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?
Figure 13 Figure Skating Medal counts
final int COUNTRIES = 7; final int MEDALS = 3; int[][] counts = new int[COUNTRIES][MEDALS];
int[][] counts = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } };
int medalCount = counts[3][1];
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 }
Figure 14 Accessing an Element in a Two-Dimensional 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(); }
Figure 15 Neighboring Locations in a Two-Dimensional Array
int total = 0; for (int j = 0; j < MEDALS; j++) { total = total + counts[i][j]; }
int total = 0; for (int i = 0; i < COUNTRIES; i++) { total = total + counts[i][j]; }
Country Gold Silver Bronze Total Canada 1 0 1 2 China 1 1 0 2 Germany 0 0 1 1 Korea 1 0 0 1 Japan 0 1 1 2 Russia 0 1 1 2 United States 1 1 0 2
int[][] board = new int[8][8];
Using two nested loops, initialize the board so that zeros and ones alternate, asfor (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { board[i][j] = (i + j) % 2; } }
ArrayList<String> names = new ArrayList<String>();
import java.util.ArrayList;
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"
Figure 17 Adding an Array List Element with add
String name = names.get(2); // Gets the third element of the array list
int i = names.size(); name = names.get(i); // Error
names.set(2, "Carolyn");
names.add(1, "Ann")
names.remove(1);
System.out.println(names); // Prints [Emily, Bob, Carolyn]
Figure 18 Adding and Removing Elements in the Middle of an Array List
ArrayList<String> names = . . . ; for (String name : names) { System.out.println(name); }
for (int i = 0; i < names.size(); i++) { String name = names.get(i); System.out.println(name); }
ArrayList<String> friends = names; friends.add("Harry");
Figure 19 Copying an Array List Reference
ArrayList<String> newNames = new ArrayList<String>(names);
ArrayList<String> names = new ArrayList<String>(); |
Constructs an empty array list that can hold strings. |
names.add("Ann"); names.add("Cindy"); |
Adds elements to the end. |
System.out.println(names); |
Prints [Ann, Cindy]. |
names.add(1, "Bob"); |
Inserts an element at index 1. names is now [Ann, Bob, Cindy]. |
names.remove(0); |
Removes the element at index 0. names is now [Bob, Cindy]. |
names.set(0, "Bill"); |
Replaces an element with a different value. names is now [Bill, Cindy]. |
String name = names.get(i); |
Gets an element. |
String last = names.get(names.size() - 1); |
Gets the last element. |
ArrayList<Integer> squares = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { squares.add(i * i); } |
Constructs an array list holding the first ten squares. |
Double wrapper = 29.95;
double x = wrapper;
Figure 20 A Wrapper Class Variable
double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }
double largest = values.get(0); for (int i = 1; i < values.size(); i++) { if (values.get(i) > largest) { largest = values.get(i); } }
ArrayList<Double> inputs = new ArrayList<Double>(); while (in.hasNextDouble()) { inputs.add(in.nextDouble()); }
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. } }
If the element at index i matches the condition Remove the element. Else Increment i.
int i = 0; while (i < words.size()) { String word = words.get(i); if (word.length() < 4) { words.remove(i); } else { i++; } }
Please enter values, Q to quit: 35 80 115 44.5 Q 35 80 115 <== largest value 44.5
ArrayList<Integer> primes = new ArrayList<Integer>(); primes.add(2); primes.add(3); primes.add(5); primes.add(7); primes.add(11);
for (int i = primes.size() - 1; i >= 0; i--) { System.out.println(primes.get(i)); }
ArrayList<String> names = new ArrayList<String>; names.add("Bob"); names.add(0, "Ann"); names.remove(1); names.add("Cal");
ArrayList<String> names; names.add(Bob);
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);
String[] weekdayNames = { "Monday", "Tuesday", "Wednesday", "Thursday", “Friday”, "Saturday", "Sunday" };
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"); } }
Generic tester:
30 10 20 5
java ScoreTester < input1.txt
Final score: 30 Expected: 30
java ScoreTester < input1.txt > output1.txt