BUILDING JAVA PROGRAMS CHAPTER 7: ARRAYS 1. 2 OUT-OF-BOUNDS INDEXES The indexes that are legal to...
-
Upload
jeffry-allen -
Category
Documents
-
view
215 -
download
0
description
Transcript of BUILDING JAVA PROGRAMS CHAPTER 7: ARRAYS 1. 2 OUT-OF-BOUNDS INDEXES The indexes that are legal to...
BUILDING JAV
A PROGRAMS
C H A P T E R 7: A
R R A Y S
1
2
OUT-OF-BOUNDS INDEXESThe indexes that are legal to access in an array are those in
the range of 0 to the array's length - 1. Reading or writing any index outside this range will throw an ArrayIndexOutOfBoundsException.
Example:int[] data = new int[10];System.out.println(data[0]); // okaySystem.out.println(data[-1]); // exceptionSystem.out.println(data[9]); // okaySystem.out.println(data[10]); // exception
2
index
0 1 2 3 4 5 6 7 8 9
value
0 0 0 0 0 0 0 0 0 0
3
THE ARRAYS CLASSThe Arrays class in package java.util has several useful static
methods for manipulating arrays:
3
Method name DescriptionbinarySearch(array, value) returns the index of the given value
in this array (< 0 if not found)equals(array1, array2) returns true if the two given arrays
contain exactly the same elements in the same order
fill(array, value) sets every element in the array to have the given value
sort(array) arranges the elements in the array into ascending order
toString(array) returns a string representing the array, such as "[10, 30, 17]"
4
ARRAYS.TOSTRINGThe Arrays.toString method is useful when you want to print an
array's elements. Arrays.toString accepts an array as a parameter and returns the String
representation, which you can then print. Example:int[] a = {2, 5, 1, 6, 14, 7, 9};for (int i = 1; i < a.length; i++) { a[i] += a[i - 1];}System.out.println("a is " + Arrays.toString(a));Output:a is [2, 7, 8, 14, 28, 35, 44]
4
5
ARRAY TRAVERSALtraversal: An examination of each element of an
array.
Traversal algorithms often take the following form:for (int i = 0; i < <array>.length; i++) { do something with <array> [i];}
Traversals are useful in many situations: printing the elements of an array searching an array for a specific value rearranging the elements of an array computing the sum, product, etc. of an array's elements ...
5
6
PRINTING ARRAY ELEMENTSExample (print each element of an array on a line):int[] myarray = {4, 1, 9, 7};for (int i = 0; i < myarray.length; i++) { System.out.println(i + ": " + myarray[i]);}Output:0: 41: 12: 93: 7
How could we change the code to print the following?4, 1, 9, 7(Do not use Arrays.toString.)
6
7
EXAMINING ARRAY ELEMENTSExample (find the largest even integer in an array):int[] list = {4, 1, 2, 7, 6, 3, 2, 4, 0, 9};int largestEven = 0;for (int i = 0; i < list.length; i++) { if (list[i] % 2 == 0 && list[i] > largestEven) { largestEven = list[i]; }}System.out.println("Largest even: " + largestEven);Output:Largest even: 6
7
8
STRING TRAVERSALStrings are like arrays of chars; they also use 0-based
indexes. We can write algorithms to traverse strings to compute information:// string stores voters' votes// (R)epublican, (D)emocrat, (I)ndependentString votes = "RDRDRRIDRRRDDDDIRRRDRRRDIDIDDRDDRRDRDIDD";int[] counts = new int[3]; // R -> 0, D -> 1, I -> 2for (int i = 0; i < votes.length(); i++) { char c = votes.charAt(i); if (c == 'R') { counts[0]++; } else if (c == 'D') { counts[1]++; } else { // c == 'I') counts[2]++; }}System.out.println(Arrays.toString(counts));
Output:[17, 18, 5]
8
9
OUTPUT PARAMETERSoutput parameter: An array or object passed as a parameter that has its
contents altered by the method.
We can pass in an array to a method and the method can change its contents in useful ways for us.
Examples: The methods Arrays.fill and Arrays.sort.
int[] nums = {4, -1, 2, 7, 3, 6};System.out.println(Arrays.toString(nums));Arrays.sort(nums); // modifies contents of numsSystem.out.println(Arrays.toString(nums));Arrays.fill(nums, 42);System.out.println(Arrays.toString(nums));
Output:[4, -1, 2, 7, 3, 6][-1, 2, 3, 4, 6, 7][42, 42, 42, 42, 42, 42]
9
10
ARRAYS AS RETURN VALUESAn array can also be returned from a method.
Syntax (declaration):public static <type>[] <name>(<parameters>) {
Example:public static int[] readAllNumbers(Scanner input) {
Syntax (call):<type>[] <name> = <method name>(<parameters>);
Example:Scanner fileScan = new Scanner(new File("temp.dat"));int[] numbers = readAllNumbers(fileScan);
10
11
ARRAY RETURN EXAMPLEExample (digit-counting problem from an earlier slide):public static int[] countDigits(int n) { int[] counts = new int[10]; while (n > 0) { int digit = n % 10; n = n / 10; counts[digit]++; } return counts;}
public static void main(String[] args) { int number = 229231007; int[] tally = countDigits(number); System.out.println(Arrays.toString(tally));}
Output:[2, 1, 3, 1, 0, 0, 0, 1, 0, 1]
11
12
STRING METHODS WITH ARRAYSThese String methods return arrays:String s = "long book";
12
Method name Description ExampletoCharArray() separates this string
into an array of its characters
s.toCharArray() returns {'l', 'o', 'n', 'g', ' ', 'b', 'o', 'o', 'k'}
split(delimiter)
separates this string into substrings by the given delimiting string
s.split(" ") returns{"long", "book"}
s.split("o") returns{"l", "ng b", "", "k"}
13
STRING/ARRAY PROBLEMSWrite a method named areAnagrams that accepts two Strings as
parameters and returns whether those strings contain the same letters (in any order).
areAnagrams("bear", "bare") returns true areAnagrams("sale", "sail") returns false Use the methods from the previous slide, as well as any relevant methods from
the Arrays class.Write a method named wordCount that accepts a String as its parameter
and returns the number of words in that string. Words are separated by spaces.
wordCount("the quick brown fox") returns 4
Use the methods from the previous slide.
13
SHIFTING ELEMENTS IN
AN
ARRAYrea
ding: 7.4
14
15
CONCEPT OF AN ARRAY ROTATIONImagine we want to 'rotate' the elements of an array; that is, to shift
them left by one index. The element that used to be at index 0 will move to the last slot in the array. For example, {3, 8, 9, 7, 5} becomes {8, 9, 7, 5, 3}.
Before:
After:
Shifting elements is useful when inserting and removing values from arrays after they have already been filled with data.
15
index 0 1 2 3 4
value 3 8 9 7 5
index 0 1 2 3 4
value 8 9 7 5 3
16
SHIFTING ELEMENTS LEFTA left shift of the elements of an array:
Let's write the code to do the left shift. Can we generalize it so that it will work on an array of any size? Can we write a right-shift as well?
16
index 0 1 2 3 4
value 3 8 9 7 5
index 0 1 2 3 4
value 8 9 7 5 3
17
SHIFTING PRACTICE PROBLEMWrite a method insertInOrder that accepts a sorted array a of integers and
an integer value n as parameters, and inserts n into a while maintaining sorted order.In other words, assume that the element values in a occur in sorted ascending order, and insert the new value n into the array at the appropriate index, shifting to make room if necessary. The last element in the array will be lost after the insertion.
Example: calling insertInOrder on array {1, 3, 7, 10, 12, 15, 22, 47, 74} and value 11 produces {1, 3, 7, 10, 11, 12, 15, 22, 47}.
17