Download presentation
Presentation is loading. Please wait.
Published byMilton Terry Modified over 6 years ago
1
Outline ArrayLists standard for : shorthand version of while Admin:
Terms Test #2: Monday 15th, 5-6pm or 6-7pm Rooms: TBA Topics: Loops, Files, Defining Objects, Event Driven Input (GUIs), Note: Chapter 6 of textbook is on GUI's. It uses a more complex design than this course (it uses inheritance and private inner classes). Read it only if you find it helpful. Textbook: Ch 7 & 15 (but covers more than we do here)
2
Storing lots of values Assignment 3, Temperature Analyser:
got an ArrayList of numbers from the user Used simple for loops to step through all the numbers to add them, draw them, etc. ArrayLists allow you to work on lots of values ArrayList of numbers or Strings ArrayList of Gliders or Flowers. What more can you do with an ArrayList? Example programs with lots of values
3
Using ArrayLists How do we create a new ArrayList?
add a new value to the ArrayList? access the values in the ArrayList? change the value at an index in the ArrayList? remove a value from the ArrayList? do something to every value in the the ArrayList find out how big the ArrayList is? 1 2 3 names:
4
Using ArrayList Creating empty ArrayList:
ArrayList<String> names = new ArrayList<String>(); Must specify the type of value Can’t be int or double or boolean!!! Have to use Integer or Double or Boolean (“wrapper” objects) ArrayList<Integer> counts = new ArrayList<Integer>(); Must have the ( ) - standard constructor, with no arguments. Type of value in the ArrayList in < …. > Type of variable Constructing the ArrayList
5
Using ArrayList For all actions, call methods on the ArrayList:
size, add, get, set, remove, clear, contains, indexOf, isEmpty, … ArrayList<String> names = new ArrayList<String>(); names.add(“Jim”); names.add(“Jan”); if (names.get(0).equals(“Jim”) { names.set(0, “Jane”); … names.add(1, “Bob”); names.remove(“Bob”); names.remove(0); Adds an item at the end of the list Gets the item at a position Replaces the item at a position with a new item Adds an item at a position names: 1 2 “Jim” “Bob” “Jan” Removes item (1st occurrence) Removes item at a position
6
Acting on each item in an ArrayList:
If you want to act on each element from 0 … end ⇒ use a simple for loop: Print out all the names: for (String name : names) { UI.println( “Hello ”, name); } for (Glider glider : gliders) { glider.move(); 1 2 3 names: A B C D Doesn't change the list 1 2 3 gliders: Changes the gliders, but doesn't change the list – the gliders are still the same objects.
7
ToDo list Program import ecs100.*; import java.util.*; public class ToDo{ private ArrayList<String> allItems = new ArrayList<String>(); public ToDo(){ UI.initialise(); UI.addButton("New", this::newList); UI.addTextField("Add", this::addItem); UI.addButton("List", this::displayList); UI.addTextField("Contains", this::doContains); UI.addTextField("Remove", this::doRemove); UI.addButton("Quit", UI::quit); } public void newList(){ this.allItems = new ArrayList<String>(); // or: this.allItems.clear(); this.displayList(); public void addItem(String item){ this.allItems.add(item); public void displayList(){ UI.clearText(); UI.printf("List has %d items:\n", this.allItems.size()); for (String item : allItems){ UI.println(item); } public void doContains(String item){ if (this.allitems.contains(item)){ UI.println(item+" is in the list"); else { UI.println(item+" is not in the list"); public void doRemove(String item){ if (this.allItems.remove(item)) { UI.println(item+" was removed"); UI.println(item+" was not present");
8
ToDo list Program public void saveList(){ try{ PrintStream ps = new PrintStream(new File("todolist.txt")); for (String item : allItems){ ps.println(item); } ps.close(); catch(IOException e){UI.println("todolist.txt is broken"+e);} public void loadList(){ this.allItems.clear(); Scanner sc = new Scanner(new File("todolist.txt")); while (sc.hasNext()){ this.allItems.add(sc.nextLine()); sc.close();
9
Garden Program public class Garden { private ArrayList<Flower> flowers = new ArrayList<Flower>(); public Garden(){ UI.setMouseListener(this::doMouse); UI.addButton(“Clear”, this::doClear); UI.addButton(“Grow”, this::doGrow); UI.addButton(“Bloom”, this::doBloom); UI.addButton(“Pick”, this::doPick); } public void doMouse(String action, double x, double y){ if (action.equals(“released”)){ Flower fl = new Flower(x, y); this.flowers.add(fl); 1 2 10 30 bud 20 5 bud 73 49 bud
10
Garden program Operate on the ArrayList of Flowers:
private ArrayList<Flower> flowers = new ArrayList<Flower>(); public void doGrow(){ for (Flower flower : this.flowers) { flower.grow(); } public void doBloom(){ flower.bloom(); public void doClear(){ this.flowers.clear(); UI.clearGraphics(); 1 2 10 30 bud 20 5 bud 73 49 bud grow bloom pick clear
11
Garden program: Alternate design
Operate on a selected Flower: private ArrayList<Flower> flowers = new ArrayList<Flower>(); private Flower selectedFlower; public void doGrow(){ this.selectedFlower.grow(10); } public void doBloom(){ this.selectedFlower.bloom(); public void doDig(){ this.flowers.remove(this.selectedFlower); 1 2 10 30 bud 20 5 bud 73 49 bud grow bloom pick clear
12
Garden program : Alternate design
Operate on a selected Flower: private ArrayList<Flower> flowers = new ArrayList<Flower>(); private Flower selectedFlower; : public void doMouse(String action, double x, double y){ if (action.equals(“released”)){ for (Flower flower : this.flowers) { if (flower.touching(x, y) ) { this.selectedFlower = flower ; return ; } } // if not touching a flower, plant one this.flowers.add(new Flower(x, y)); 1 1 2 grow bloom pick dig
13
Saving a Garden to a file
Get file name and open file step through flowers, printing to file public void doSave(){ File saveFile = new File(UIFileChooser.save("File for Garden")); try{ PrintStream out = new PrintStream(saveFile); for (Flower flower : this.flowers) { out.println(flower.toString()); } out.close(); catch(IOException e) { UI.println("File saving failed: "+e); } 1 2 3 flowers: position(x,y) and state(height, stage): eg: bud
14
Loading Garden from a file
Get file name and open file Step through file, reading public void load(){ try { this.flowers = new ArrayList<Flower>(); // or this.flowers.clear(); File file = new File(UIFileChooser.open("Choose Garden File")); Scanner sc = new Scanner(file); while (sc.hasNext()){ Flower fl= new Flower(sc.nextDouble(), sc.nextDouble(), sc.nextDouble(), sc.next () ); this.flowers.add(fl); } sc.close(); catch(IOException e){UI.println("File loading failed: "+e);} bud bloom picked bud : 1 2 3 flowers:
15
Changing an ArrayList: loops
If you want to change an ArrayList, then can't use the simple for loop! Eg: Change each name to uppercase: for (String name : this.names) { name = name.toUpperCase(); } If you need to know the index of the items, can't use the simple for loop Eg: print out the todo list is numbers: for (String item : this.allItems) { UI.println( index +": " + item ); 1 2 3 names: anne bill cath dave
16
Changing an ArrayList: loops
Need to use a while loop or a standard for loop int i= 0; while (i < names.size()) { String upName = names.get(i).toUpperCase(); names.set(i, upName); i++; } for (int i= 0; i < names.size(); i++) { for (int index = 0; index < this.allItems.size(); index++) { UI.println( index +": " + item ); 1 2 3 names: anne bill cath dave Standard "for loop" Standard "for loop"
17
Standard for loops Standard for loop is just a while loop with the elements rearranged: int i = 0 ; while (i < data.size() ){ … data.get(i) … ; i = i+1 ; } The for loop is a shorthand: for (int i = 0 ; i < data.size(); i++ ) { … data.get(i) … ; Only got to this slide in 2016T1
18
Standard For loop For loop puts the together, at the front of the loop
intialisation once, before the loop body is run at all condition tested each time, before loop body run increment run each time, after loop body run together, at the front of the loop But the meaning is (almost) exactly the same as the while loop (scope of variables in initialisation is different) Initialisation Condition Increment for ( statement ; expression ; statement ) statement
19
Removing items from an ArrayList in a loop
Remove gliders past the right edge: for (Glider glider : this.gliders) { if (glider.getX() >= RIGHT_EDGE) { gliders.remove(glider); } Must use a standard for loop (or while loop) for (int index = 0 ; index < this.gliders.size(); index++) { Glider glider = this.gliders.get(index); this.gliders.remove(glider); BE CAREFUL WHEN MODIFYING THE LIST IN A LOOP! Program will CRASH! Not allowed to change the list while iterating with a "for each" loop up to here at 12pm Won't crash, But still won't work properly! 1 2 3 gliders:
20
Removing items from ArrayList in a loop
Step back after removing item for (int num = 0 ; num < gliders.size(); num++) { if (gliders.get(num).getX() >= RIGHT_EDGE) { gliders.remove(num); num = num - 1; } Or iterate backwards from the end. for (int num = gliders.size()-1 ; num >= 0; num--) { gliders.remove(num);} 1 2 3 gliders: up to here at 10am.
21
Menu More ArrayLists: Administration: ICT Careers fair today,
Tutorial on Tuesdays 5pm (Kirk 202!) Test next Monday I used bluej to demonstrate the Numbers program early in lecture. Rest of lecture is going through the design process and explaining the code. It is important to do the design process, not just present the resulting code.
22
More Examples of Methods on ArrayLists
mylist.size() returns the number of items in mylist. Note contrast to String: .size() vs .length() UI.printf("The garden had %d flowers\n", this.flowers.size()); mylist.add(item) adds the item at the end of the ArrayList balloons.add( new Balloon(x, y, color) ); mylist.add(index, item) inserts the item at position index ( 0 .. size ) int pos = UI.askInt(“Where do you want ” +name); receptionOrder.add(pos, name); item must be of the right type item must be of the right type 1 2 3 receptionOrder: 4 “Jim” “Ann” “Cary” “Bob”
23
More Examples of Methods on ArrayLists
mylist.get(index) returns the item at position index (0 .. size-1) mylist.set(index, item) replaces the current value at position index with item returns the old value at index index must be size-1 UI.print(“Which two units do you want to swap?”); int first = UI.askInteger("first"); int scnd = UI.askInteger("second"); String temp = attackList.get(first); attackList.set(first, attackList.get(scnd)); attackList.set(scnd, temp); attackList.set(first, attackList.set(scnd, attackList.get(first))); Got to here on Friday. if (first>=0 && first< attackList.size() && scnd>=0 && scnd<attackList.size() && first!=second){ Or
24
More Examples of Methods on ArrayLists
mylist.isEmpty() returns true iff there are no items in mylist. // Make each unit advance, if there are any units if ( ! attackList.isEmpty() ) { for (Unit unit : attackList) { unit.checkPath(); unit.advance(3); } mylist.clear() removes all values from the list. // Restart and clear the list of all elements. public void doRestart() { UI.clearGraphics(); this.flowers.clear();
25
More Examples of Methods on ArrayLists
mylist.contains(item) returns true if the item is somewhere in mylist mylist.remove(item) removes the item, if it is present, and shuffles later items down returns true iff item was removed // Respond to a “Remove Person” button String name = UI.askString("Person to remove"); if (receptionOrder.contains(name)){ receptionOrder.remove(name); } else { UI.println("That person is not in the reception order"); if ( ! receptionOrder.remove(name) ){ first occurrence of item if item is at several places in the list “Bill” Or 1 2 3 receptionOrder: 4 “Jim” “Cary” “Bob” “Ann”
26
More Examples of Methods on ArrayLists
mylist.indexOf(item) returns the position of item in mylist returns –1 if the item is not present // Report position on waiting list String name = UI.askString("Your name:"); int index = waitingList.indexOf(name); if (index == –1) { UI.println("You are not on the waiting list"); } else { UI.println("You are number " + index + " in order"); } mylist.remove(index) removes the item at position index (0 .. size-1) returns the value that was removed // Remove every third unit from attackList for (int index=2; index<attackList.size(); index = index+3){ attackList.remove(index); } 1 2 3 attackList: 4 5 6 7 8 9 10 11
27
Using ArrayLists of numbers
public void analyseNumbers(String fileName){ ArrayList<Double> nums = new ArrayList<Double>(); try { Scanner sc = new Scanner(new File(fileName)) while (sc.hasNextDouble()){ nums.add(sc.nextDouble()); } sc.close(); } catch(IOException e){UI.println(“Reading numbers failed: "+e);} double max = Double.NEGATIVE_INFINITY; for (double num : nums) { if ( num > max) { max = num; UI.printf("%.3f is the largest of %d numbers\n", max, nums.size()); Read numbers into ArrayList Step through numbers to find largest
28
Patterns There are many common patterns for working with arrays or ArrayLists. Do something with 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.
29
"Any" pattern: Finding a value
Search array or ArrayList 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; return true; return false; s0 s11 s5 s8 s2 s4 s10 (field) names: s1 s3 s6 s7 s9 s12 default answer if no such element the answer if you find one no else clause! why not? why keep searching once you know the answer? default answer: if no element was equal
30
"All" pattern: Check valid
Check ArrayList of names: all must have at least one space in them public boolean checkValidNames(ArrayList<String> names){ boolean allOK= true; for (int i = 0; i < names.size() ; i++){ if ( ! names.get(i).contains(" ") ) { allOK = false; break; } return allOK; for (String nm : names){ if ( ! nm.contains(" ") ) { return false; return true; default: answer if all pass to here at 10am the answer if one fails.
31
Working on multiple items at once
Doing something to each adjacent pair Given an array with a list of numbers, check if in order: public boolean checkOrdered(ArrayList<Double> data){ for ( int i = 0; i<data.size()–1; i++){ if ( data.get( i ) > data.get(i+1)){ return false; } return true; for (int i = 1; i<data.size(); i++){ if ( data.get( i-1 ) > data.get( i ) ){ data: 51 67 68 68 79 78 82 90 Can’t use ‘for each’! compare with next item: stop before length-1 compare with previous item: start at 1
32
Working on multiple items at once
smoothi = 0.25 datai datai datai+1 “Smooth” the data: Given a list of numbers, generate a new list: public ArrayList<Double> smooth(ArrayList<Double> data){ ArrayList<Double> answer = new ArrayList<Double>(); answer.add( 0.67*data.get(0) *data.get(1) ); // first element is special for (int i = 1; i<data.size() –1; i++){ answer.add( 0.25 * data.get( i-1) * data.get( i) * data.get( i+1) ); } answer.add( 0.33 * data.get(data.size() – 2) * data.get(data.size()-1); // last element return answer; data: 51 67 68 68 79 78 82 90
33
Changing the order: reverse
Reverse all the elements in an array/ArrayList public void reverseList( ){ for (int i = 0; i < this.cartoons.size()/2; i++){ CartoonCharacter temp = this.cartoons.get( i ); this.cartoons.set( i, this.cartoons.get(this.cartoons.size() – 1 – i); this.cartoons.set (this.cartoons.size() – 1 – i , temp); } Or public void reverseList(){ for (int i = 0; i<this.cartoons.size()/2; i++){ cartoons.set( i, cartoons.set(cartoons.size() – 1 – i), cartoons.get( i) ) ); cartoons: cc1 cc5 1 cc3 2 cc8 3 cc2 4 cc6 5 cc4 6 set returns the old value at the position!!
34
Acting on every pair of values
gliders: Given ArrayList with Gliders check if any two Gliders are colliding with each other: (assume Glider class has a method called isTouching) for ( int i=0; i<this.gliders.size(); i++ ){ for ( int j=0; j< this.gliders.size(); j++ ){ if (this.gliders.get( i ).isTouching(this.gliders.get( j ) ){ //do something } for (int i=0; i<this.gliders.size(); i++){ for (int j=i+1; j<this.gliders.size(); j++){ if ( this.gliders.get( i ).isTouching(this.gliders.get( j )) ){ g1 g5 g3 g8 g2 g6 g4 What’s the problem?
35
Arrays vs ArrayLists Some lists have a fixed number of places:
The places may be empty Arrays may be more convenient than using ArrayLists
36
SeedTray Program: just 12 flowers
3 4 5 6 7 8 9 10 11 length: 12 null from uploads/2010/04/tps_seedlings.jpg
37
Arrays An array is an object with a sequence of a fixed number places
Length determined when array is created) All elements are of the same type Special syntax, no methods Each element specified by its index (an int expression) seedtray[ 4 ] ← name of the element of shapes with index 4 seedtray[ n-3 ] Counting from 0, just like ArrayLists! Array knows its length: seedtray.length 1 2 3 4 5 6 7 8 9 10 11 length: 12 seedTray: Confusion: names.size() ← ArrayList name.length() ← String tray.length ← Array
38
Declaring and Creating Arrays
Declare a variable to hold an array object by putting [ ] after the type of the elements: Flower[ ] seedtray; String[ ] keywords; private double[ ] marks; Create an array object with new and the length of the array: new Flower[12]; new String[50]; new double[200]; As usual, can combine declaration and initialisation: String [ ] keywords = new String [50]; What does the new array contain? Creates a place that can hold an array Doesn’t create the array itself NO ROUND BRACKETS !!! Creates an array object Doesn’t declare a variable to hold it
39
Initial values in a new array
Arrays of objects initialised with null (the “no object here” value) Arrays of numbers initialised to 0. seedtray: null null null null null null null null null null null null 1 2 3 4 5 6 7 8 9 10 11 length: 12 marks: . . . 1 2 3 4 5 6 7 8 199 length: 200
40
No ‘Array’ in declaration!
SeedTray Program public class SeedTray { private Flower[ ] seedtray = new Flower[12]; No ‘Array’ in declaration! seedtray: null null null null null null null null null null null null 1 2 3 4 5 6 7 8 9 10 11 length: 12
41
Using an array Can act on the whole array to pass to a method
to assign to another variable : this.processFlowers(seedtray); int maxNum = this.findMax(numbers); int [ ] windowSizes = numbers; Note, passing as argument and assignment do not copy the array! (just the reference/ID of the object) Just the same as with ArrayList. numbers: length: public int findMax(int[] nums){ …
42
Index can be any int valued expression
Using an Array Use [ .. ] to refer to an individual place in the array to access the value in that place to put a value in that place (using assignment: = ) double [ ] marks = new double [200]; int n=4; : marks[5] = 45.6; marks[6] = ( marks[5] + marks[7] ) / 2; marks[n-1] = 80.0; marks[n] = marks[n-1]; if (marks[ i ] == marks[ i+1 ]) {… Not get() and set() 0.0 0.0 0.0 80.0 0.0 0.0 80.0 0.0 45.6 0.0 22.8 0.0 0.0 . . . 0.0 1 2 3 4 5 6 7 8 199 Note about index range added later – was explained during the lecture. length 200 Index can be any int valued expression
43
SeedTray Program public class SeedTray{ private Flower[ ] seedtray = new Flower[12]; : public void replant(){ for (int i = 0; i < this.seedtray.length; i++) { this.seedtray[ i ] = new Flower(70+i*50, 400); } public void growAll(){ public void growAll(){ for (int i = 0; i < this.seedtray.length; i++) { for (Flower flower : this.seedtray){ this.seedtray[ i ].grow(); flower.grow(); } } 1 2 3 4 5 6 7 8 9 10 11 length:12 seedtray:
44
Initialising the contents of an array
Can specify the initial values (and size) of an array by listing the values in {.. , .. , ..} : String [ ] names = new String [ ] { “Ian”, “Pondy”, “Monique” , “Zarinah” }; int [ ] dimensions = new int [ ] { 20, 45, 8 }; Can’t do this with ArrayLists! names: 1 2 3 “Pondy” “Monique” “Zarinah” “Sharon” length: 4 dimensions: 1 2 length: 3 45 8 20
45
Arrays vs ArrayList Use an array if Use an ArrayList if
it will never change size, and you know how big it will need to be, at the point you need to create it. Use an ArrayList if the size will change, or you don’t know how big it will need to be. Arrays have convenient syntax [ ] ArrayLists have convenient methods.
46
Saving a SeedTray to a file
Get file name and open file Write size of array Step through seedtray, printing flowers or null to file public void doSave(){ try{ PrintStream out = new PrintStream(new File(UIFileChooser.save("File for Seedtray"))); out.println(this.seedtray.length); for (Flower flower : this.seedtray) { out.println(flower); } out.close(); catch (IOException e) { UI.println("File saving failed: "+e); } 4 bud null picked bud : 1 2 3 seedtray: println( object ) calls the toString() method automatically. if (flower == null) { out.println("null"); } else { out.println(flower.toString(); } Assumes that Flower has a toString method that returns a String in the form bud
47
Loading Seedtray from a file
4 bud null picked bud : Get file name and open file Read the size & make array Step through file, reading public void load(){ try { Scanner sc = new Scanner(new File(UIFileChooser.open("Choose Seedtray File"))); this.seedtray = new Flower [ sc.nextInt() ]; for (int i = 0; i < this.seedtray.length; i++ ){ if (sc.hasNextInt()) { this.seedtray[i] = new Flower( sc.nextInt(), sc.nextInt(), sc.nextInt(), sc.next () ); } else { sc.next(); } sc.close(); catch (IOException e){UI.println("File loading failed: "+e);} 1 2 3 seedtray: Assumes that Flower has a constructor that has parameters for all the fields to reconstruct a Flower
48
Flower Class import ecs100.*; import java.awt.Color; public class Flower{ // fields private double baseX; private double baseY; private double height; private String stage; /** constructor for planting; given position */ public Flower(double x, double y){ this.baseX = x; this.baseY = y; this.stage = "Bud"; this.height = 20; } /** additional constructor; for reconstructing flower */ public Flower(double x, double y, double h, String s){ this.baseX = x; this.baseY = y; this.stage = s; this.height = h;} /** returns text description of the Flower*/ public String toString(){ return ( this.baseX + " " + this.baseY + " " + this.height + " " + this.stage ); …
49
Arrays with Meaningful Indices
Sometimes, the index represents meaningful information 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 n1 n5 n8 n10 n7 n3 n6 n4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 -1 700 620 460 450 380 220 510 480 1 2 3 4 5 6 7 8 9 10 2 9 16 3 1 15 8 4 10 5 6 7 4 89 6 90 91 85 86 87 7 2 3 92 1
50
null: the “not-a-real-object” value.
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 free public boolean isFree(int room){ return (this.guests[room]==null); n1 n5 n8 n10 n7 n3 n6 n4 guests: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 null: the “not-a-real-object” value. Can always be assigned to a place of an object type half way through slide at 12noon lecture Don’t need to step through array!
51
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]) ) … n1 n5 n8 n10 n7 n3 n6 n4 guests: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Problem if null! How do we fix it?
52
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; n1 n5 n8 n10 n7 n3 n6 n4 guests: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Example of "Any" pattern
53
Find an empty room Find the index of an empty room (return -1 if no empty rooms) public int findEmpty(){ 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; n1 n5 n8 n10 n7 n3 n6 n4 guests: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 to here at 10am lecture What’s the problem? How do we fix it?
54
Arrays of Counts To keep track of numbers we have seen, efficiently
Counting the number of occurrences of each number a file of integers: Scanner sc = new Scanner(new File(FileDialog.open("file to check"))); int[ ] numbersSeen = new int[100]; while ( sc.hasNext() ){ if ( sc.hasNextInt() ){ int num = sc.nextInt(); if ( num>=0 && num<100 ){ numbersSeen[num] = numbersSeen[num] + 1; // OR numbersSeen[num]++; } else{ sc.next(); Initialised with 0 2 9 16 3 1 15 8 4 10 5 6 7 99 ⋯
55
Comparing arrays. Be careful when comparing arrays (as with all objects) int[ ] a = new int[ ]{ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 43, 47}; int[ ] b = new int[ ]{ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 43, 47}; int[ ] c = b; if (a == b) .. ?? no if (b == c) .. ?? yes if (a.equals(b) ) .. ?? no if (Arrays.equals(a, b) ) .. ?? yes if (this.arrayEquals(a, b) ) .. ?? yes public boolean arrayEquals(int[ ] a, int[ ] b) { if (a==null && b==null ) { return true; } if (a==null || b==null ) { return false; } if ((a.length != b.length ) { return false; } for (int i = 0; i < a.length; i++) { if ( a[i] != b[i] ) { return false; } } return true; }
56
Main method main takes an array of strings as a parameter:
Can be used to provide “command line inputs” to a program, eg. the name of a file to process. May be optional: public static void main(String[ ] args) { String fname; if ( args.length > 0 ) { fname = args[0]; } else { fname = UIFileChooser.open("Data files"); } try { Scanner scan = new Scanner (new File(fname)); while (scan.hasNext()) { … } catch (IOException e){ …… } > java Plotter mynumbers.txt
57
2D arrays COMP 102 # T1
58
Menu Some more array details 2D arrays Administration
59
2D Data data in rows and columns 2 4 8 X O ID A1 A2 A3 A4 30012 30031
30048 30056 30080 30118 30185 30302 30345 30382 30495 30515 30545 X O 2 4 8 Mon Tue Wed Thu Fri Sat Sun 9-10 10-11 11-12 12-1 1-2 2-3 3-4 4-5
60
2D arrays: Creating 2D arrays require two indices, and two sizes
Declaring and creating: int[ ] [ ] marks = new int [200][4]; ChessPiece[ ][ ] board = new ChessPiece [8][8]; Color[ ][ ] image = new Color [100][150]; int[ ][ ] matrix = new int [ ][ ]{{2, 4, 3},{5, 8, 4}, {8, 4, 9}}; First index, second index : which is the row and which is the column? You choose! Choose your variable names carefully. Typically use first index as the row.
61
2D arrays: Accessing Assigning and accessing:
marks[10][3] = 72; board[row][col] = board[row][col-1]; board[row][col-1] = null; for (int row=0; row<height; row++){ for (int col=0; col<width; col++){ image[row][col] = image[row][col].darker(); } In Java, can’t use commas image[row, col]
62
2D arrays 2D arrays are actually arrays of arrays:
int[ ] [ ] marks = new int[200] [4]; is the same as int[ ] [ ] marks = new int[200] [ ]; for (int i = 0; i<200; i++){ marks[i] = new int[4]; } marks 1 2 3 4 5 6
63
2D arrays: length Number of rows and columns in a 2D array?
int[ ] [ ] marks = new int[200] [4]; marks.length (number of rows) marks[row].length 4 (number of columns) If the first index is the row! to here on Monday 10am marks 1 2 3 4 5 6
64
We don’t use these in COMP102!
2D arrays Can have non-square arrays: int [ ] [ ] table = new int [7] [ ]; for (int row = 0; row<7; row++){ table[row] = new int [row+1]; } We don’t use these in COMP102! table 1 2 3 4 5 6
65
Processing 2D arrays Typically use nested for loops to process each item public void printTable( String[ ][ ] grades){ for (int row=0; row< grades.length; row++){ for (int col=0; col< grades[row].length; col++){ UI.printf(" %-2s ", grades[row][col]); } UI.println(); for (String[ ] row : grades){ for (String grade : row){ UI.printf(" %-2s ", grade); A+ B- A- B B+ C A B- A D A+ A A- B+ B+ B A A- C+ C+ To here on thursday '-' flag means left justified If not modifying the array, can use foreach loops, but must be careful!
66
Drawing a 2D array ♖ ♔ ♘ ♗ ♙ ♜ ♝ ♚
public void drawBoard(ChessPiece[ ][ ] board){ int rows = board.length; int cols = board[0].length; for (int row=0; row<rows; row++){ int y = TOP + SIZE*row; for (int col=0; col<cols; col++) { int x = LEFT + SIZE*col; UI.setColor( (row%2==col%2) ? Color.gray : Color.white); UI.fillRect(x, y, SIZE, SIZE); if (board[row][col] !=null) { board[row][col] .draw(x, y); } }♔♕♗♖♘♙♚♛♜♝♞♟ UI.setColor(Color.black); UI.drawRect(LEFT, TOP, SIZE * rows, SIZE * cols); Shorthand for: if (row%2==col%2) { UI.setColor(Color.gray); } else { UI.setColor(Color.white); ♖ ♔ ♘ ♗ ♙ ♜ ♝ ♚ Make ChessPiece draw itself
67
Printing a table with headers
public void printTable(long[ ] IDs, String[ ][ ] grades){ int rows = grades.length; int cols = grades[0].length; UI.print(" ID |"); for (int col=0; col<cols; col++) { UI.printf(" A%d |", col); } UI.println(); for (int col=-1; col<cols; col++) { UI.print("----+"); } for (int row=0; row<rows; row++){ UI.printf("%4d|", IDs[row]) UI.printf(" %-2s |", grades[row][col]); } } Assumes all rows same length ID | A1 | A2 | A3 | A4 | 3012| A+ | B- | A- | B | 3052| B+ | C | A | B- | 3029| A | D | A+ | A | 3172| A- | B+ | B+ | B | 3094| A | A- | C+ | C+ |
68
Moving value in a 2D array
public void moveUp(ChessPiece[ ][ ] board, int row, int col){ if ( row > 0 && row < board.length && col >= 0 && col < board[row].length && board[row][col] != null && board[row-1][col] == null ) { board[row-1][col] = board[row][col]; board[row][col] = null;♗♖♘♙♚♛♜♝♞♟ } 1 2 3 4 5 6 7 1 2 3 4 5 6 7 ♖ ♔ ♘ ♗ ♙ ♜ ♝ ♚
69
Moving all values in a 2D array
public void flipBoard(ChessPiece[ ][ ] board){ int rows = board.length; int cols = board[0].length; for (int row=0; row<rows/2; row++){ for (int col=0; col<cols; col++) { ChessPiece temp = board[row][col]; board[row][col] = board[rows-row-1][col]; board[rows-row-1][col] = temp; }} } to here on thurs 12noon 1 2 3 4 5 6 7 1 2 3 4 5 6 7 ♖ ♔ ♘ ♗ ♙ ♜ ♝ ♚ 1 2 3 4 5 6 7 ♜ ♚ ♝ ♙ ♗ ♔ ♘ ♖
70
Rotating (cw) all values in a 2D array
♖ ♔ ♘ ♗ ♙ ♜ ♝ ♚ public void rotateBoard(ChessPiece[ ][ ] board){ int rows = board.length; int cols = board[0].length; ChessPiece[ ][ ] temp= new ChessPiece[rows][cols]; for (int row=0; row<rows; row++){ for (int col=0; col<cols; col++) { temp[row][col] = board[row][col]; }} int srow = cols-col-1; int scol = row; board[row][col] = temp[srow][scol]; } 1 2 3 4 Make a temporary copy of the source, to avoid "losing" values. 5 90º 6 7 10am Thursday to here 1 2 3 4 5 6 7 1 2 3 4 5 6 7 ♗ ♜ ♝ ♔ ♖ ♙ ♚ ♘ For each cell in the result, work out where its value comes from.
71
Processing multiple arrays
public double[ ][ ] matrixAdd(double[ ][ ] a, double[ ][ ] b){ int rows = a.length; int cols = a[0].length; if (b.length!=rows || b[0].length!=cols) { return null; } double[ ][ ] ans = new double[rows][cols]; for (int row=0; row<rows; row++){ for (int col=0; col<cols; col++){ ans[row][col] = a[row][col] + b[row][col]; } return ans; 2 4 5 6 3 2 5 1 4 7 8 7 4 9 6 2 + =
72
Processing multiple arrays
public double[ ][ ] matrixMultiply(double[ ][ ] a, double[ ][ ] b){ int rows = a.length; int cols = b[0].length; if (cols != b.length) { return null; } double[ ][ ] ans = new double[rows][cols]; for (int row=0; row<rows; row++){ for (int col=0; col<cols; col++){ for (int i=0; i<b.length; i++){ ans[row][col] = ans[row][col]+a[row][ i ] * b[ i ][col]; } return ans; 2 4 5 6 3 2 5 1 4 7 6+4+6 4+16+0 8+20+0 * =
73
Saving a 2D array to a file
Write the grade table to a file: A B B+ A- B- C+ Writing the dimensions of the array first will help. Three people with 4 assignments each or Four people with 3 assignments each Six people with 2 assignments each A B B+ A- B- C+ A B B+ A- B- C+ A B B+ A- B- C+
74
Saving a 2D array to a file
Writing the dimensions in the file helps: public void saveTable( String[][] grades, String fileName){ try{ PrintStream file =new PrintStream(new File(fileName)); int rows = grades.length; int cols = grades[0].length; file.println(rows + " " + cols); for (int row=0; row<rows; row++){ for (int col=0; col<cols; col++){ file.println(grades[row][col]); } }catch(IOException e){UI.println("Table saving failed: "+e);} Print number of rows and columns on first line of file.
75
Saving a 2D array to a file
Alternate design: assume file has been opened elsewhere and passed as argument use "foreach" because not modifying the array. public void saveTable( String[ ][ ] grades, PrintStream file){ file.println(grades.length + " " + grades[0].length); for (String[ ] row : grades){ for (String grd : row){ file.println(grd); } Note, you could pass System.out to the method to make it print to the terminal window! (useful for debugging)
76
Loading 2D array from a file
Assume first two tokens of file are the dimensions: public String[ ][ ] loadTable( ){ try { Scanner sc = new Scanner(new File(UIFileChooser.open())); int rows =sc.nextInt(); int cols = sc.nextInt(); String[ ][ ] ans = new String[ rows ][ cols ]; for (int row=0; row<rows; row++){ for (int col=0; col<cols; col++){ ans[row][col] = sc.next(); } return ans; } catch(IOException e){UI.out.println("Table loading failed: "+e);} return null;
77
Loading 2D array from a file
Alternate, assuming scanner is passed as argument array is stored in a field public void loadTable(Scanner sc ){ this.dataArray = new String[ sc.nextInt() ] [ sc.nextInt() ]; for (int row=0; row<this.dataArray.length; row++){ for (int col=0; col<this.dataArray[row].length; col++){ this.dataArray[row][col] = sc.next(); }
78
Another file format for 2D arrays
Suppose the array has only a few entries and many nulls ie, a "sparse" array Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 1 T1 2 lects 3 Better to save just the non-null entries 4 5 lects lects 6 Study 7 8 9 10 Exam 11 end T3 T2 12 end Ex Grad 13 14 15 16 17 Grad Study 18 Break 19
79
File format size (months, days) [note: first and second index, not rows and columns!] month day entry To load: read size and create calendar array read month, day, entry, and assign entry to calendar[month][day] To save: print size for each non-null entry, print month, day, entry 12 32 0 5 lects end T3 2 1 T2 break :
80
Load sparse array public void loadSparse(){ try{
Scanner sc = new Scanner( new File(UIFileChooser.open())); int months= sc.nextInt(); int days = sc.nextInt(); this.calendar = new String[months][days]; while (sc.hasNext()){ int month = sc.nextInt(); int day = sc.nextInt() String entry = sc.next(); this.calendar[month][dayl] = entry; } sc.close(); catch (IOException e){UI.println("Fail: " + e);} Don't know how many entries there will be!
81
Save sparse array public void saveSparse(){ try{ PrintStream ps = new PrintStream(new File(UIFileChooser.save())); ps.println(this.calendar.length+" "+ this.calendar[0].length); for (int month = 0 ; month < this.calendar.length; month++){ for (int day = 0 ; day< this.calendar[month].length; day++){ if (this.calendar[month][dayl] != null){ ps.println(month+" "+day+" "+this.calendar[month][dayl]); } sc.close(); catch (IOException e){UI.println("Fail: " + e);}
82
Doing without UI & ecs100 library #1
UI class lets you print and read from the text pane What do you do without the UI? Output: System.out is the "terminal window". You can print/println/printf to System.out, just like UI System.out.println("Here is a message for you"); Input: System.in is the keyboard via the "terminal window" You have to wrap it with a Scanner to read: Scanner userInput= new Scanner(System.in); : System.out.print("Enter age: "); int age = userInput.nextInt(); No "ask…()" methods
83
Doing without UI & comp102 library #2
How do you make a window with a text area, and buttons? Using Swing: Have to make a JFrame object and set its size Make a JTextArea object and add to frame Make a JPanel and add to frame Make JButtons and add to the panel make button add listener add to panel Make the frame visible Define methods to respond to events. Writing to the text area is different.
84
DemoInterface import javax.swing.*; import java.awt.event.*; import java.awt.BorderLayout; public class DemoInterface { private JFrame frame = new JFrame("Demo program"); private JTextArea textOut = new JTextArea(30, 30); public DemoInterface () { this.frame.setSize(600, 400); this.frame.add(this.textOut, BorderLayout.CENTER); JPanel panel = new JPanel(); this.frame.add(panel, BorderLayout.SOUTH); JButton button1 = new JButton("Doit"); button1.addActionListener(this::doIt); panel.add(button1); JButton button2 = new JButton("Clear"); button2.addActionListener((ActionEvent e)->{textOut.setText(“”);}); panel.add(button2); this.frame.setVisible(true); }
85
DemoInterface public void doIt(ActionEvent e) { for (int i = 1; i <=10; i++){ this.textOut.append(i+ " squared is " + (i*i)); }
86
Makeup Assignment: GoGame
Very simple program One field Constructor One button One Mouse action redisplay method Key idea: program from scratch – no template code.
87
BalloonGame Simple game Key data structure: Collection of Balloons
Clicking on a Balloon expands it If two Balloons touch, they pop. Score = total area of live balloons minus area of popped Balloons. Key data structure: Like DominoGame: needs a list of Balloon objects: Could use ArrayList <Balloon> Balloon[ ] (array of Balloon)
88
BalloonGame Simple game Key data structure: Collection of Balloons
Clicking on a Balloon expands it If two Balloons touch, they pop. Score = total area of live balloons minus area of popped Balloons. Key data structure: Like DominoGame: needs a list of Balloon objects: Could use ArrayList <Balloon> Balloon[ ] (array of Balloon) Actually want two lists: live balloons popped balloons
89
BalloonGame
90
Design of BalloonGame
91
Types and Interface Variables, fields, array elements, ArrayList elements are all defined with a type Only values of the specified type can be put into a place What types are there primitive types: int, double, boolean, long, float, char, .. note: java will "coerce" some types: double number = 4; Object types: Arrays : int[ ], double[ ][ ], Balloon[ ], ArrayLists: ArrayList<Integer>, ArrayList<ArrayList<Double>>, ArrayList<Balloon>, Predefined: String, Color, File, Scanner, … Programmer defined: CartoonFigure, Balloon, BalloonGame, … Type of object determined at its creation: new Balloon(100, 300) ⇒ a Balloon object new File ("data.txt") ⇒ a File object new int[100][100] ⇒ an array of arrays of int. Every class defines a type
92
Object types All object values have two types:
the type they were created as the Object type You can have a place of type Object: Object value = new Balloon(100, 100); value = "not any more"; ArrayList<Object> things = new ArrayList<Object>(); things.add("more“); things.add( new Balloon(100, 100), new Double(4.5)); for (Object thing : things){ UI.println(thing.toString()); System.out.println(thing); }
93
Object types There are limits on what you can do with a place of type Object: value.pop(); value.toUpperCase(); for (Object thing : things){ if (thing.startsWith(“Ball”){ System.out.println(thing); } You can only call methods on the value in a variable/field if the methods belong to the type of the variable/field. value.toString() Won't work if value contains a String Won't work if value contains a Balloon Won't work if value contains a Balloon
94
Collections of different types
Extending the Balloon Game: several kinds of balloons: ordinary balloons – expand uniformly, and pop on touching bomb balloons – blow up, taking out lots of balloons at max size long balloons – expand into sausage shapes, popping other balloons only, up to limit bouncy balloons – don't expand, but bounce around T
95
New Balloon Game BalloonGame needs ArrayLists to hold all the balloons
Each class of balloons needs the same methods: expand, on, pop, touches but, they each behave differently. BalloonGame ArrayList of balloons ArrayList of popped balloons RoundBalloon expand() on(int x, int y) touches(…) pop() BombBalloon expand() on(int x, int y) touches(…) pop() LongBalloon expand() on(int x, int y) touches(…) pop() BouncyBalloon expand() on(int x, int y) touches(…) pop()
96
BalloonGame public class BalloonGame { :
Can use Object Can use Object public class BalloonGame { : private ArrayList < > balloons = new ArrayList< > (); public void doClick(double x, double y){ for ( b : this.balloons){ if ( b.on(x, y) ) { b.expand(); Object Object RoundBalloon-2 BombBalloon-5 BouncyBalloon-3 LongBalloon-8 RoundBalloon-18 RoundBalloon-7 LongBalloon-9 Object Java compiler will complain! No such method for Object Java will complain! No such method for Object
97
Different Balloon classes
public class RoundBalloon { private double x, y; private double radius = 10; private Color col; public void expand(){ this.radius += 3;) public boolean on(double u, double v){ return ( Math.hypot(this.x – u, this.y –v) < this.radius ); } public class LongBalloon { private double length = 0; private double direction = Math.PI * 2 * Math.random(); private Color color; public void expand(){ this.length += 10; } return …. ;
98
Casting Can sometimes convert a value from one type to another
numbers: int col = (int) (x /cellWidth); double x = 100 * col; Must be an explicit cast if information might be lost. anything to a string: (by adding to a string) "value is " + x For an Object value, it automatically calls the toString() method "value is " + x.toString() any object value from one of its types to another Object balloon = (Object) ( new RoundBalloon(34, 45) ); RoundBalloon rb = (RoundBalloon) balloon; object must be of that type, otherwise a runtime error got to here on friday, but not talked this slide
99
"Generic" values with Object
public class BalloonGame { : private ArrayList<Object> balloons = new ArrayList<Object> (); public void doClick(double x, double y){ for (Object b : this.balloons){ RoundBalloon rb = (RoundBalloon) b; if ( rb.on(x, y) ) { rb.expand(); RoundBalloon-2 BombBalloon-5 BouncyBalloon-3 LongBalloon-8 RoundBalloon-18 RoundBalloon-7 LongBalloon-9 Cast it to a RoundBalloon Now compiler is happy But if b is a BombBalloon or… the program will fall over!
100
"Generic" values with Object
public void doClick(double x, double y){ for (Object b : this.balloons){ if (b instanceof RoundBalloon) { RoundBalloon rb = (RoundBalloon) b; if (rb.on(x, y) ) { rb.expand();…..} } else if (b instanceof LongBalloon) { LongBalloon lb = (LongBalloon) b; if (lb.on(x, y) ) { lb.expand();…..} else if (b instanceof BombBalloon) { BombBalloon lb = (BombBalloon) b; … RoundBalloon-2 BombBalloon-5 BouncyBalloon-3 LongBalloon-8 RoundBalloon-18 RoundBalloon-7 LongBalloon-9 instanceof checks if the value is of the specified type Correct, but not nice!
101
A Balloon type RoundBalloon, LongBalloon, BombBalloon, BouncyBalloon are all kinds of Balloon. ⇒ should all be of a Balloon type. RoundBalloon-2 should be a a RoundBalloon, a Balloon, and an Object public class BalloonGame { private ArrayList<Balloon> balloons = new ArrayList<Balloon> (); public void doClick(double x, double y){ for (Balloon b : this.balloons){ if ( b.on(x, y) ) { b.expand(); …
102
Making a Balloon Type Problem: What is "a Balloon" ? Answer 1:
Something you can expand, public void expand() ask if a point is on it, public boolean on(int x, int y) pop public void pop() ask if touching a balloon public boolean touches(Balloon other) ask for its size public double size() Answer 2: a RoundBalloon, or a LongBalloon, or a BombBalloon, or a BouncyBalloon. We need to make both answers true. Balloon RoundBalloon LongBalloon BouncyBalloon BombBalloon
103
Interface classes An interface class describes a supertype of other types. It specifies a name for the type the headers for the methods that any object of the type can respond to. constants (public static final double GRAVITY = 9.8) No constructors! public interface Balloon { method headers constants } You cannot make a new instance of an interface. Balloon b = new Balloon(); An interface just says "what"; not "how"
104
A Balloon Interface class.
public interface Balloon { public void expand(); public boolean on(double x, double y); public void pop(); public double size(); public boolean touches(Balloon other); } Declares a type that you can use for fields,variables, arrays: public class BalloonGame { private int maxBalloons = 20; private ArrayList<Balloon> balloons = new ArrayList<Balloon>(); public void doClick(double x, double y){ for (Balloon b : this.balloons){ if (b.on(x, y) ) { b.expand(); Note the ; instead of { …. } Java will NOT complain! Balloons DO have these methods
105
Making a Balloon Type Problem: What is "a Balloon" ?
Answer 1: Defined by interface Balloon { Something you can expand, ask if a point is on it, pop ask for its size ask if touching a balloon Answer 2: a RoundBalloon, or a LongBalloon, or a BombBalloon, or a BouncyBalloon. We need to make both answers true.
106
Making classes have another type
If you define some class, all instances are automatically of type Object also. To make instances also be of some interface type: declare that the class implements the interface type: make sure that the class defines all the methods specified by the interface type: public class RoundBalloon implements Balloon { private double x, y; private double radius = 10; private Color col; public void expand(){ …… } public boolean on(double x, double y){ …… } public void pop() { …… } public double size() { …… } public boolean touches(Balloon other) { …… } } implements is a “promise” that these objects will be of the interface type. ie, will have all the methods. Must provide method bodies, not just headers!
107
More classes implementing Balloon
public class LongBalloon implements Balloon { private double x, y; private double length = 10; private double dir = 1.26; private Color baseCol, tubeCol; public void expand(){ …… } public boolean on(double x, double y){ …… } public void pop() { …… } public double size() { …… } public boolean touches(Balloon other) { …… } } public class BombBalloon implements Balloon { private double x, y, maxRad; private double radius = 10; private Color col;
108
Making a Balloon Type Problem: What is "a Balloon" ?
Answer 1: Defined by interface Balloon { Something you can expand, ask if a point is on it, pop ask for its size ask if touching a balloon Answer 2: Specified by … implements Balloon a RoundBalloon, or a LongBalloon, or a BombBalloon, or a BouncyBalloon. We have now made both answers true.
109
BalloonGame class structure
User Interface ArrayList of Balloon Balloon RoundBalloon expand pop … LongBalloon expand pop … BombBalloon expand pop … BouncyBalloon expand pop …
110
Interface class summary
If you define an interface class: You have defined a type You can declare variables (or arrays) to have that type. You cannot make an object of the interface class new Balloon(…) // NOT ALLOWED (there is no constructor) Objects from classes implementing the interface are of that type. You can call any of the specified methods on values in fields/variables of that type. When defining an interface class: You should include headers of methods You may include static final constants You may not include ordinary fields, constructors, or ordinary method bodies.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.