1 / 17

Building Java Programs

Building Java Programs. Chapter 7: Arrays. Out-of-bounds indexes. The 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:

rmichaud
Download Presentation

Building Java Programs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Building Java Programs Chapter 7: Arrays

  2. Out-of-bounds indexes • The 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]); // okay System.out.println(data[-1]); // exception System.out.println(data[9]); // okay System.out.println(data[10]); // exception

  3. The Arrays class • The Arrays class in package java.util has several useful static methods for manipulating arrays:

  4. Arrays.toString • The 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 (inti = 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]

  5. Array traversal • traversal: An examination of each element of an array. • Traversal algorithms often take the following form: for (inti = 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 • ...

  6. Printing array elements • Example (print each element of an array on a line): int[] myarray= {4, 1, 9, 7}; for (inti = 0; i < myarray.length; i++) { System.out.println(i + ": " + myarray[i]); } Output: 0: 4 1: 1 2: 9 3: 7 How could we change the code to print the following? 4, 1, 9, 7 (Do not use Arrays.toString.)

  7. Examining array elements • Example (find the largest even integer in an array): int[] list = {4, 1, 2, 7, 6, 3, 2, 4, 0, 9}; intlargestEven = 0; for (inti = 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

  8. String traversal • Strings 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)ndependent String votes = "RDRDRRIDRRRDDDDIRRRDRRRDIDIDDRDDRRDRDIDD"; int[] counts = new int[3]; // R -> 0, D -> 1, I -> 2 for (inti = 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]

  9. Output parameters • output 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 nums System.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]

  10. Arrays as return values • An 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);

  11. Array return example • Example (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]

  12. String methods with arrays • These String methods return arrays: String s = "long book";

  13. String/array problems • Write 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.

  14. Shifting elements in an array reading: 7.4

  15. Concept of an array rotation • Imagine 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.

  16. Shifting elements left • A 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?

  17. Shifting practice problem • Write 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}.

More Related