ITI 1221 Introduction to Computing II Lab7 Dewan
ITI 1221. Introduction to Computing II Lab-7 Dewan Tanvir Ahmed University of Ottawa
Today’s Objective q q Understanding the current Assignment, e. g. Assignment 3 Reviewing the solution of Assignment 2 Reviewing the solution of Mid term GUI and Event Driven Programming
Assignment 3 q Objectives o Further understanding of exception handling in Java o Learn about two implementations of Queues o Introduction to Queue-based algorithms Ø Breath-First Search (BFS) algorithm
Assignment 3 (cont. . ) Exceptions o Create a new exception type called Empty. Queue. Exception Ø A subclass of Runtime. Exception Ø The class Empty. Queue. Exception has two constructors – A default constructor with no parameters – A constructor with a parameter of type String, » which is used to save a reference to an error message for later retrieval by the get. Message method
Assignment 3 (cont. . ) Exceptions o Create a new exception type called Queue. Overflow. Exception Ø A subclass of Runtime. Exception Ø The class Queue. Overflow. Exception has two constructors – A default constructor with no parameters – A constructor with a parameter of type String, which is used to save a reference to an error message for later retrieval by the get. Message method
Assignment 3 (cont. . ) Exceptions o modify the methods of the classes Linked. Queue and Circular. Queue Ø To validate the pre-conditions and Ø throw the appropriate exception when needed: – Empty. Queue. Exception, – Queue. Overflow. Exception and – Illegal. Argument. Exception
Assignment 3 (cont. . ) Copy o The method copy() creates a duplicate of a queue containing the same elements and be in the same order o It creates a copy of a queue such that the values of the queue and its copy are shared, Shallow copy. o Class Linked. Queue: public Linked. Queue copy() Ø Adding elements to a linked structure having a front reference and rear reference Ø You can’t use the instance methods of this class to implement this method Ø NB. Two queues are sharing the values but not the nodes o Class public Circular. Queue copy() Ø Exercise of wrapping front and rear around the boundaries Ø You can’t use the instance methods of this class to implement this method Ø The elements of the duplicate should be stored at positions 0 to size - 1
Assignment 3 (cont. . ) public boolean equals( Object other ) Override the method public boolean equals( Object other ) Ø It returns – true if other designates a Queue (any implementation of the interface Queue) that contains the same number of elements as this queue, and each element of the other queue must be “equals” to the corresponding element in this queue – false otherwise Ø Both queues must not be changed by the method equals, i. e. before and after a call to the method equals, this and the other queue must contain the same elements, in the same order
Assignment 3 (cont. . ) Test o Write a Test program for the methods copy and equals of the classes Ø Linked. Queue and Ø Circular. Queue.
Assignment 3 (cont. . ) q Questions? ? ? (Linked. Queue, Circular. Queue) Ø Ø Ø Size Wrapping Enqueue Dequeue Empty! Full!
Assignment 3, Part II q Queue Based Algorithms o BFS
Assignment 3, Part II (cont. . ) q Class HTML o HTML document = new HTML( "http: //www. site. uottawa. ca/~turcotte/a 3/" ); int count=0; while ( document. has. More. Urls() ) { String url = document. next. Url(); count++; } System. out. println( "This document has " + count + " links. " ); o How to get the content Ø document. get. Page();
Assignment 3, Part II (cont. . ) q Class Solution o A Solution has two instance variables (both of type String). Ø One that designates the path represented by the solution. Ø The other stores the last URL of the path represented by the solution; o Constructors Ø The constructor Solution( String last. Url ) – sets both instance variables to last. Url. Ø The constructor Solution( Solution partial, String last. Url ) – sets the path of this Solution to that of partial concatenated with last. Url; – path = partial. getpath() -> last. Url Ø It also sets the instance variable for the last URL of this object to last. Url; o A solution has two access methods, Ø get. Path and Ø get. Las. Url
Assignment 3, Part II (cont. . ) Crawler o The class Crawler contains three static methods that are used to find a path from a Web page A to a Web page B o private static boolean is. Valid( String url ) Ø returns true – if url is a well formed URL designating an existing/readable Web page, and false otherwise. Use the fact that the constructor of an HTML object Ø Throws an exception, of type Malformed. URLException, – if the url is not well formed Ø Throws an exception, of type IOException, – if the content of the page cannot be successfully read o Any Question?
Assignment 3, Part II (cont. . ) Crawler o private static Solution solve( String a, String b ) Ø Implement a breath-first search algorithm for finding a path from a Web page A to a Web page B. Ø The breath-first search uses a Queue data structure (this can be your own implementation of Linked. Queue) Ø The algorithm initializes the queue to contain just the partial solution that consists of the Web page A only, and repeatedly does the following: – dequeues a partial solution off the queue; – extend the partial solution by one URL in all possible ways – enqueues each of the “valid” extension
Assignment 3, Part II (cont. . ) Crawler o public static void main( String[] args ) Ø The main method prints the following message unless there are exactly two arguments on the command line, and exists immediately – Usage: java Crawler src dst Ø If the command line has two arguments, those arguments are used for calling the method solve Ø The main method prints the path if it exists, and “no path” if no such path was found
Solution – Assignment 2 q Let’s Go o Click here
Mid-Term Solution - Q 1
Mid-Term Solution Q 1 (cont. . ) q Part A o Implement the three classes, as well as the interface Player. Ø Make sure to include the constructors Ø For each attribute – write the access methods – The values of the attributes must be valid » If the value of the parameter is less than 0. 0 then set the value of the attribute to 0. 0 » Similarly, if the value of the parameter is larger than the upper limit then set the attribute to its upper limit Ø Finally, implement the methods attack
Mid-Term Solution Q 1 (cont. . ) Implementation of interface Player: o All players of the game have a method double attack() that returns a value representing the strength of the attack. o Player is an interface declaring the method double attack() public interface Player { public abstract double attack(); }
Mid-Term Solution Q 1 (cont. . ) Implementation of abstract class Abstract. Player: o An Abstract. Player defines the characteristics that are common to all the creatures o This abstract class implements the interface Player o All the creatures have Ø A name (a character String) Ø A life meter (a double ranging from 0. 0 to 100. 0) – The initial value of the life meter is 50. 0 o Implement constructor method o Implement access methods Ø getters and setter methods for attributes name and life meter
Mid-Term Solution Q 1 (cont. . ) public abstract class Abstract. Player implements Player { private static final double LIFE_METER_INIT = 50. 0; private static final double LIFE_METER_MAX = 100. 0; private static final double LIFE_METER_MIN = 0. 0; private String name; private double life. Meter; public Abstract. Player( String name ) { life. Meter = LIFE_METER_INIT; this. name = name; } public String get. Name() { return name; } public String set. Name( String name ) { this. name = name; } public double get. Life. Meter() { return life. Meter; }
Mid-Term Solution Q 1 (cont. . ) public void set. Life. Meter( double value ) { life. Meter = value; if ( life. Meter < LIFE_METER_MIN ) { life. Meter = LIFE_METER_MIN; } else if ( life. Meter > LIFE_METER_MAX ) { life. Meter = LIFE_METER_MAX; } } }
Mid-Term Solution Q 1 (cont. . ) Class Uldra o An Uldra is a creature (player) that carries a bottle filled with poison (a double value in the range 0. 0. . . 100. 0) o Uldra creatures have a tendency to misplace their bottles (a boolean value indicates if this Uldra has or not its bottle) o The strength of an attack is zero if the Uldra has no bottle. Otherwise, the strength of an attack is 10. 0, or the remaining amount of poison (which ever value is smaller) o The strength of the attack reduces the quantity of poison left by the same amount
Mid-Term Solution Q 1 (cont. . ) public class Uldra extends Abstract. Player { private boolean has. ABottle; private double poison; public Uldra( String name ) { super( name ); has. ABottle = false; poison = 0. 0; } public boolean has. ABottle() { return has. ABottle; } public void set. Has. Bottle( boolean value ) { has. ABottle = value; if ( ! has. ABottle ) { poison = 0. 0; } } public double get. Poison() { return poison; }
Mid-Term Solution Q 1 (cont. . ) public void set. Poison( double value ) { if ( has. ABottle ) { poison = value; if ( poison < 0. 0 ) { poison = 0. 0; } else if ( poison > 100. 0 ) { poison = 100. 0; } } } public double attack() { double result = 10. 0; if ( ! has. ABottle ) { result = 0; } else if ( get. Poison() < result ) { result = get. Poison(); } set. Poison( get. Poison() - result ); return result; } }
Mid-Term Solution Q 1 (cont. . ) Class Yakku o Yakku creatures have magical powers (double, range 0. 0. . . 100. 0, the initial value is 10. 0) o The strength of the attack depends on both its life meter and its magical powers. Specifically, a weight w is calculated as being the value of the life meter divided by 10. 0 o The weight w is then multiplied by the level of magical powers to obtain the strength of the attack o An attack reduces both the life meter and the magical powers by the strength of the attack.
Mid-Term Solution Q 1 (cont. . ) public class Yakku extends Abstract. Player { private static final double MAGIC_POWERS_MAX = 100. 0; private static final double MAGIC_POWERS_MIN = 0. 0; private static final double MAGIC_POWERS_INIT = 40. 0; private double magic. Powers = MAGIC_POWERS_INIT; public Yakku( String name ) { super( name ); } public double get. Magic. Powers() { return magic. Powers; } public void set. Magic. Powers( double value ) { magic. Powers = value; if ( magic. Powers < MAGIC_POWERS_MIN) { magic. Powers = MAGIC_POWERS_MIN; } else if ( magic. Powers > MAGIC_POWERS_MAX ) { magic. Powers = MAGIC_POWERS_MAX; } }
Mid-Term Solution Q 1 (cont. . ) public double attack() { double w = get. Life. Meter() / 10. 0; double result = w * magic. Powers; set. Life. Meter( get. Life. Meter() - result ); magic. Powers = magic. Powers - result; return result; } }
Mid-Term Solution Q 1 (cont. . ) Part B o Write a polymorphic class method, duel, that has two parameters, both of type Abstract. Player, first and second. o Rules Ø While both players are alive (i. e. their life meter is greater than zero) Ø The first player launches an attack onto the second one Ø If the second player is still alive, it launches an attack onto the first player Ø When a player “a” launches an attack onto a player “b”, you must reduce the value of the life meter of “b” by a. attack() Ø Finally, the method displays the name of the player that is still alive
Mid-Term Solution Q 1 (cont. . ) public static void duel( Abstract. Player first, Abstract. Player second ) { while ( first. get. Life. Meter() > 0. 0 && second. get. Life. Meter() > 0. 0 ) { double strength; strength = first. attack(); second. set. Life. Meter( second. get. Life. Meter() - strength ); if ( second. get. Life. Meter() > 0. 0 ) { strength = second. attack(); first. set. Life. Meter( first. get. Life. Meter() - strength ); } } Abstract. Player alive = first; if ( second. get. Life. Meter() > 0. 0 ) { alive = second; } System. out. println( alive. get. Name() + " is alive!" ); }
Mid-Term Solution Q 2 Calculator c = new Calculator(); c. execute( "40 5 2 4 1 ~ print + print ^ print * print - print" ); -top. INTEGER: -1 INTEGER: 4 INTEGER: 2 INTEGER: 5 INTEGER: 40 -bottom-top. INTEGER: 3 INTEGER: 2 INTEGER: 5 INTEGER: 40 -bottom- -top. INTEGER: 8 INTEGER: 5 INTEGER: 40 -bottom-top. INTEGER: 0 -bottom
Mid-Term Solution Q 3 q Correct at least 5 mistakes (logic, runtime or compile-time errors) in the partial implementation q "implements Stack" missing q constructor o declaration of a local variable elems masks the instance variable elem o ’capacity = capacity’ should be o ’this. capacity = capacity’, otherwise, the instance variable capacity will not be initialized o this. increment not assigned q increase. Size o needs a for loop to copy the elements or System. arraycopy q Pop o should decrease size then access the element o "return saved" missing o (should be calling decrease. Size after removing the element. )
Mid-Term Solution Q 3 (cont. . ) q Complete the partial implementation of the class Dynamic. Array. Stack public void push( Object element ) { if (size == elems. length) { increase. Size(); } elems[ size ] = element; size = size + 1; }
Mid-Term Solution Q 3 (cont. . ) q Complete the partial implementation of the class Dynamic. Array. Stack private void increase. Size() { Object[] new. Elems; new. Elems = new Object[elems. length + increment]; // Copying all the elements to the new array new. Elems = elems; // Replacing elems with the new and larger array elems = new. Elems; }
Mid-Term Solution Q 3 (cont. . ) q Complete the partial implementation of the class Dynamic. Array. Stack public Object pop() { size = size - 1; Object saved = elems[ size ]; // Scrubbing the memory! elems[ size ] = null; if (elems. length > capacity && ( elems. length - size ) >= increment) { decrease. Size(); } return saved; }
Mid-Term Solution Q 3 (cont. . ) q Complete the partial implementation of the class Dynamic. Array. Stack private void decrease. Size() { int new. Size = elems. length - increment; if ( new. Size < capacity ) { new. Size = capacity; } Object[] new. Elems; new. Elems = new Object[ new. Size ]; for ( int i=0; i<size; i++ ) { new. Elems[ i ] = elems[ i ]; } // Replacing elems with the new/smaller array elems = new. Elems; }
Mid-Term Solution Q 4 q In the class Combination. Lock, override the method equals. o Two locks are equals if Ø Their status are “equals” and both Combination. Lock have the same combination (defined by the variables first, second and third) Ø Otherwise, the method returns false o No values are considered illegal; in particular, the method should be handling null values.
Mid-Term Solution Q 5 (cont. . ) public boolean equals( Object obj ) { if ( obj == null || ! ( obj instanceof Combination. Lock ) ) return false; Combination. Lock other = (Combination. Lock) obj; boolean result = true; if ( first != other. first ) result = false; else if ( second != other. second ) result = false; else if ( third != other. third ) result = false; else if ( status == null ) result = ( other. status == null ); else result = status. equals( other. status ); return result; }
Mid-Term Solution Q 6 q Linked. Pair - Part A q Draw the memory diagram representing the content of the memory after the execution of the following statement Pair p = new Linked. Pair ( new Name("Joseph", "Rotblat"), new Name("Wangari", "Maathai"));
Mid-Term Solution Q 5 (cont. . ) q Linked. Pair - Part B q For the partial implementation of the class Linked. Pair, write the instance method public sort() that sorts the (two) elements of a Linked. Pair q Rules o o Change the order of the elements (objects of the class Elem) exchanging the values of the nodes is not acceptable. public void sort() { if ( first. value. compare. To( first. next. value ) > 0 ) { Elem new. First = first. next; new. First. next = first; first. next = null; first = new. First; } }
Mid-Term Solution Q 5 (cont. . ) q Part C q Complete the implementation of the method String to. String(). It returns a String representation of the pair o o o starting with “(” Followed by the String representation of the first object of the pair Followed by “, ” Followed by the String representation of the second object of the pair Followed by “)”. public String to. String() { return "(" + first. value + ", " + first. next. value + ")"; }
Mid-Term Solution Q 6 q Part A o Define a new checked exception called Zenda. IOException. o This should be a specialized IOException. public class Zenda. IOException extends IOException { public Zenda. IOException() { super(); } public Zenda. IOException( String message ) { super( message ); } }
Mid-Term Solution Q 6 (cont. . ) import java. io. File. Input. Stream; import java. io. File. Not. Found. Exception; public class Zenda { private static void get. Config( String name ) throws Zenda. IOException { if ( name == null ) { throw new Illegal. Argument. Exception( "null value" ); } File. Input. Stream input; try { input = new File. Input. Stream( name ); } catch ( File. Not. Found. Exception e ) { throw new Zenda. IOException( "file not found: " + name ); } }
Mid-Term Solution Q 6 (cont. . ) private static void init() throws Zenda. IOException{ get. Config( "config. dat" ); } public static void main( String[] args ) { try { init(); } catch ( Zenda. IOException e ) { System. err. println( "ERROR READING CONFIG FILE" ); e. print. Stack. Trace(); System. exit( 1 ); } } }
Mid-Term Solution (cont. . ) q Part C o Explain why a runtime exception will occur if the following statements are executed. public class Manager { Null. Pointer. Exception? private Object[] elems; public Manager( int capacity ) { if ( elems. length == 0 ) { elems = new Object[ capacity ]; } } public static void main( String[] args ) { Manager m = new Manager( 100 ); } }
GUI and Event Driven Programming q Any component can be the source of an event o A button generates an event when you click on it. q Any class can be a listener for an event o It simply implements the method (s) of the interface q The object that handles the event generated from the click of a button needs to implement the interface Action. Listener. q The object that handles the event generated when a window is closed must implement the interface Window. Listener.
GUI and Event Driven Programming (cont. . ) q The event generated by the source component is sent to the listeners who registered with the component. q The source has a method add. Action. Listener who needs as a parameter an object that implements the interface Action. Listener. q Since the handler implements the interface Action. Listener, the source knows that the handler has a method action. Performed(. . . ). q Example o private Display. Area display = new Display. Area(); o button. add. Action. Listener(display); Object Source Listener Registration
GUI and Event Driven Programming (cont. . ) import java. awt. *; import java. awt. event. *; public class GUI extends Frame { private Button b. Left = new Button("Left"); private Button b. Right = new Button("Right"); private Display. Area display = new Display. Area(); public GUI() { super("DGD - Week 8"); set. Background(Color. WHITE); add(display, Border. Layout. CENTER); Panel p = new Panel(); p. add(b. Left); p. add(b. Right); add(p, Border. Layout. SOUTH);
GUI and Event Driven Programming (cont. . ) b. Left. add. Action. Listener(display); b. Right. add. Action. Listener(display); add. Window. Listener(new Window. Adapter() { public void window. Closing(Window. Event e) { System. exit(0); } } ); pack(); show(); } public static void main(String[] args) { new GUI(); } }
GUI and Event Driven Programming (cont. . ) import java. awt. *; import java. awt. event. *; class Display. Area extends Canvas implements Action. Listener { private Point center; Display. Area() { set. Size(200, 200); center = new Point(100, 100); } public void paint(Graphics g) { g. set. Color(Color. RED); g. fill. Oval(center. x - 5, center. y - 5, 10); } public void action. Performed(Action. Event e) { String cmd = e. get. Action. Command(); if (cmd. equals("Left")) { center. x = (center. x + 190) % 200; // subtracts 10 } else if (cmd. equals("Right")) { center. x = (center. x + 10) % 200; } repaint(); } }
Window. Adapter q A Frame has a method add. Window. Listener that allows you to register an object that implements the interface Window. Listener. q The interface lists 7 methods: o o o o public void window. Opened(Window. Event e); public void window. Closing(Window. Event e); public void window. Closed(Window. Event e); public void window. Iconified(Window. Event e); public void window. Deiconified(Window. Event e); public void window. Activated(Window. Event e); public void window. Deactivated(Window. Event e); q Still, in order to register a handler with the frame we have to provide an object that implements this interface, o which means that we have to implement the 7 methods
Solution - Window. Adapter Solution - 1: All the methods are empty except for window. Closing: import java. awt. event. *; class My. Window. Listener implements Window. Listener { public void window. Opened(Window. Event e) {} public void window. Closing(Window. Event e) { System. exit(0); } public void window. Iconified(Window. Event e) {} public void window. Deiconified(Window. Event e) {} public void window. Activated(Window. Event e) {} public void window. Deactivated(Window. Event e) {} }
Solution - Window. Adapter Solution -2 1. 2. Inherit all the empty methods and implements the ones we need for this application. class My. Window. Adapter extends Window. Adapter { public void window. Closing(Window. Event e) { System. exit(0); } }
The End
- Slides: 55