Download presentation
Presentation is loading. Please wait.
Published byDwayne Wright Modified over 9 years ago
1
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington “For each” & Patterns with Arrays/ArrayLists COMP 102 #24 2014 T1
2
© Peter Andreae COMP 102 24:2 Menu Another form of for. Common patterns with arrays and ArrayLists all and any operating on pairs Admin: Test: 5-6pm tonight: A - Gibbs: HM LT205 (Hugh McKenzie, across the bridge) Giles - Pasa: KK LT303 (Kirk, just on Hub side of Bridge) Patel - Z: MC LT103 (Maclaurin, next to the Hub) students doing PHYS 114 : 6-7pm in MC LT103
3
© Peter Andreae COMP 102 24:3 Acting on each item in array: Step along array, acting on each value eg: array of names: public void printAll(String [ ] names ){ for (int i = 0; i<names.length; i++){ String n = names[ i ]; UI.println(n); } } public void printAll(String [ ] names ){ for (String n : names){ UI.println(n); } } 12345500 length: 50 bensalkitann may jandon ⋯ names: n: array passed in as a parameter “ For each ” loop Steps through each item in array n:
4
© Peter Andreae COMP 102 24:4 "For each" loop Special form of the for loop: Goes through every element of the array or ArrayList (0 to length-1) The variable is assigned the next element of the array automatically each time round. Contrast with ordinary for Can't use “for each” to change the array: The variable contains a copy of the value in the array, Changing the variable does not change the the array itself. for( type { statement :) array / ArrayList } variable for( init { cond ) incre ;;
5
© Peter Andreae COMP 102 24:5 For each object in an ArrayList…. “for each” is ok when using values in arrays and ArrayLists public void redraw( ){ for (Flower flower : this.flowers){ if ( flower != null) { flow.draw(); } 12345??0 ⋯ flower: flowers :
6
© Peter Andreae COMP 102 24:6 Changing each object in an Array…. “for each” is NOT safe when changing values public void printAll(String [ ] names ){ for (String name : names){ name = name + “ Junior”; } } 12345500 length: 50 ⋯ names : ben sal kit ann may jan don name:
7
© Peter Andreae COMP 102 24:7 Acting on each item: Same for numbers: private double[ ] marks; public double averageMark(){ double sum = 0; for (int i = 0; i<this.marks.length; i++){ sum = sum + this.marks[ i ]; } return sum / this.marks.length; } public double averageMark(){ double sum = 0; for (double mk : this.marks){ sum = sum + mk; } return sum / this.marks.length; } Field, accessible to all methods in class. Given value in another method
8
© Peter Andreae COMP 102 24:8 Changing each item? Can’t use “for each” loop to change the array/ArrayList: private double[ ] marks; public void scaleUpMarks(double scale){ for (int i = 0; i<this.marks.length; i++){ this.marks[ i ] = this.marks[ i ] + scale; } } public void scaleUpMarks(double scale){ for (double mk : this.marks){ mk= mk + scale; } } 12345500 length: 50 56184119 27 3024 ⋯ mk:
9
© Peter Andreae COMP 102 24:9 Changing each item: Changing the ArrayList: can’t use “for each” loop private ArrayList grades; public void scaleUpGrades(){ for (int i = 0; i<this.marks.length; i++){ this.grades.set( i, this.grades[ i ] + “+”; } } public void scaleUpGrades(){ for (String grd : this.grades){ grd= grd + “+”; } } 123450 “B”“E”“B”“A” “D” “A” ⋯ grd:
10
© Peter Andreae COMP 102 24:10 Patterns There are many common patterns for working with arrays or ArrayLists. Do something with each value Change each value Search for any item that satisfies some property Check if all items have some property Do something with every adjacent pair of items. Do something with every possible pair of items.
11
© Peter Andreae COMP 102 24:11 "Any" pattern: Finding a value Search array to see if it contains a given value eg: array of names: finding if name is present in any element public boolean containsName(String name){ boolean ans = false; for (String n : this.names){ if ( n!=null && n.equals(name) ) { ans = true; } } return ans; } public boolean containsName(String name){ for (String n : this.names){ if ( n!=null && n.equals(name) ) { return true; } } return false; } default answer if no such element s0s0 s 11 s5s5 s8s8 s2s2 s4s4 s 10 names: the answer if you find one no else clause! why not? s1s1 s3s3 s6s6 s7s7 s9s9 s 12 default answer: if no element was equal
12
© Peter Andreae COMP 102 24:12 "All" pattern: Check valid Check that all values in an array satisfy some condition eg: field containing an array of marks: check all between 0 and 100 public boolean checkValidMarks(){ boolean ans = true; for (int i = 0; i < this.marks.length ; i++){ if ( this.marks[i] 100 ) { ans = false; } } return ans; } public boolean checkValidMarks(){ for (int mk : this.marks){ if ( !( mk >= 0 && mk <= 100) ) { return false; } } return true; } Reversed condition maybe easier to understand default: answer if all pass the answer if one fails.
13
© Peter Andreae COMP 102 24:13 Doing something to each adjacent pair Given an array with a list of numbers, check if in order: public boolean checkOrdered(int[ ] data){ for (int i = 0; i<data.length-1; i++){ if ( data[ i ] > data[ i+1 ] ){ return false; } } return true; } public boolean checkOrdered(int[ ] data){ for (int i = 1; i<data.length; i++){ if ( data[ i-1 ] > data[ i ] ){ return false; } } return true; } data: Working on multiple items at once 516768 79788290 length: 8 compare with next item: stop before length-1 compare with previous item: start at 1 Can’t use for each!
14
© Peter Andreae COMP 102 24:14 Acting on every pair of values Given array with BouncingBalls check if any two BouncingBalls are colliding with each other: (assume BouncingBalls have a method called isTouching) for (int i=0;i<balls.length; i++){ for (int j=0; j<ball.length; j++){ if (balls[ i ].isTouching(balls[ j ]) ){ //do something } } } for (int i=0; i<balls.length-1; i++){ for (int j=i+1; j<balls.length; j++){ if (balls[ i ].isTouching(balls[ j ])){ //do something } } } b1b1 b5b5 b3b3 b8b8 b2b2 b6b6 b4b4 balls: What ’ s the problem?
15
© Peter Andreae COMP 102 24:15 Bouncing Ball Class: colliding public class BouncingBall{ private int radius; private int centerX, centerY; private Color color; /** Returns true if this ball is touching the other ball, and false otherwise */ public boolean isTouching(BouncingBall other){ double dx = other.centerX - this.centerX; double dy = other.centerY - this.centerY; double dist = other.radius + this.radius; return (Math.hypot(dx, dy) <= dist); }
16
© Peter Andreae COMP 102 24:16 Arrays with Meaningful Indices Sometimes, the index represents meaningful information ⇒ May need to be have “empty” cells. array of guest names for hotel rooms (numbered 1 to MaxRoom) house info for each house on street count of occurrences of each number image 700620460 450380220510480 012345678910 n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 012345678910111213141516 2 9 31 15804100 0123456789 4 89 69091 858687 7 2 85 39214
17
© Peter Andreae COMP 102 24:17 Hotel Register initialise empty private String[ ] guests = new String[MaxRoom+1]; // gives indexes from 0 to MaxRoom, ignore index 0 assign to room public void assignGuest(String name; int room){ this.guests[room] = name; } look up to see if empty public boolean isEmpty(int room){ return (this.guests[room]==null); } n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 guests: 012345678910111213141516 Don ’ t need to step through array! null: the “not-a-real-object” value. Can always be assigned to a place of an object type
18
© Peter Andreae COMP 102 24:18 Hotel Register: remove Checkout guest from room /* returns true if name was checked out of room successfully, false otherwise */ public boolean checkout(String name, int room){ if ( this.guests[room].equals(name) ){ this.guests[room] = null; return true; } return false; } if ( this.guests[room] != null && this.guests[room].equals(name) ) … if ( name.equals(this.guests[room]) ) … What ’ s the problem? How do we fix it? n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 guests: 012345678910111213141516
19
© Peter Andreae COMP 102 24:19 Alternative Checkout guest: search and remove: /* returns true if name was checked out successfully, false otherwise */ public boolean checkout(String name){ for (int rm=1; rm<this.guests.length; rm++){ // or <=MaxRoom if (this.guests[rm] != null && this.guests[rm].equals(name) ) { this.guests[rm] = null; return true; } return false; } n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 guests: 012345678910111213141516
20
© Peter Andreae COMP 102 24:20 Find an empty room Find the index of an empty room (return -1 if no empty rooms) public int findEmpty(int room){ for (int rm=1; rm<this.guests.length; rm++){// or <=MaxRoom if (this.guests[rm]==null) { return rm; } } return -1; } Check a guest into an empty room (return room number) public void checkIn(String name){ this.guests[ this.findEmpty() ] = name; } public boolean checkIn(String name){ int rm = this.findEmpty(); if (rm < 0) { return false; } this.guests[rm] = name; return true; } What ’ s the problem? How do we fix it? n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 guests: 012345678910111213141516
21
© Peter Andreae COMP 102 24:21 Arrays of Booleans To keep track of numbers we have seen, efficiently Eg: looking for duplicates: read file, check and set Scanner sc = new Scanner(new File(FileDialog.open("file to check"))); boolean[ ] numbersSeen = new boolean[100000]; while ( sc.hasNext() ){ if ( sc.hasNextInt() ){ int num = sc.nextInt(); if ( num>=0 && num<100000 ){ if (numbersSeen[num] ) System.out.println(num + "is a duplicate"); else numbersSeen[num] = true; } else{ String junk = sc.next(); } Initialised with false
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.