Implementing Comparable public class Rational implements Comparable public

Implementing Comparable public class Rational implements Comparable { public int compare. To (Object obj) { final double TOLERANCE =. 0001; Rational other = (Rational) obj; double other. Rational = (double) other. numerator/ other. denominator; double this. Rational = (double) this. numerator / this. denominator; double difference = this. Rational - other. Rational; int result = 0; if (Math. abs(difference) < TOLERANCE) result = 0; else if (difference > 0) result = 1; else result = -1; return result; } }

Array An ordered list of values of the same type. n That type can be primitive or n reference (class or interface). Arrays are objects (reference types). Arrays are of fixed size and are always bound checked. The length of array: ia. length Index starts from 0. An array of size N is indexed from 0 to N-1
![Array Examples int[] ia = new int[3]; ia[0] = 1; ia[1] = 2; ia[2] Array Examples int[] ia = new int[3]; ia[0] = 1; ia[1] = 2; ia[2]](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-3.jpg)
Array Examples int[] ia = new int[3]; ia[0] = 1; ia[1] = 2; ia[2] = 3; //-----------int ia[] = new int[3]; //-----------int[] ia = { 1, 2, 3}; float[][] mat = new float[4][5]; for (int y = 0; y < mat. length; y++) { for (int x = 0; x < mat[y]. length; x++) mat[y][x] = 0. 0; } // mat. length = number of rows // mat[y]. length = number of columns in row y
![Variable length array int [][] table; table = new int[4][]; table [0] = new Variable length array int [][] table; table = new int[4][]; table [0] = new](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-4.jpg)
Variable length array int [][] table; table = new int[4][]; table [0] = new int [10]; table [1] = new int [20]; table [2] = new int [30]; table [3] = new int [40]; int max = 0; for (int i = 0; i < table. length; i++) for (int j = 0; j < table[i]. length; j++) if (table[i][j] > max) max = table [i][j];
![4 Dimensional array int [][] table = new int[5][6][7][8]; . . . int a, 4 Dimensional array int [][] table = new int[5][6][7][8]; . . . int a,](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-5.jpg)
4 Dimensional array int [][] table = new int[5][6][7][8]; . . . int a, b, c, d, max = 0; for (a = 0; a < table. length; a++) for (b = 0; b < table[a]. length; b++) for (c = 0; c < table[a][b]. length; c++) for (d = 0; d < table [a][b][c]. length; d++) if (table[a][b][c][d] > max) max = table [a][b][c][d];

Arrays as Parameters An array reference can be passed as a parameter during a method call All reference parameters create aliases Changing an array element in the method changes the original

Arrays of Objects The elements of an array can be object references The following declaration reserves space to store 25 references to String objects String[] words = new String[25]; The declaration does NOT create the String objects themselves Each object stored in an array must be instantiated separately
![Example: Grade. Range. java public class Grade. Range { public static void main (String[] Example: Grade. Range. java public class Grade. Range { public static void main (String[]](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-8.jpg)
Example: Grade. Range. java public class Grade. Range { public static void main (String[] args) { String[] grades = {"A", "A-", "B+", "B-", "C+", "C-", "D+", "D-", "F"}; int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0}; for (int level = 0; level < cutoff. length; level++) System. out. println (grades[level] + "t" + cutoff[level]); } }
![Example: Words class Words { public static void main (String[] args) { String title; Example: Words class Words { public static void main (String[] args) { String title;](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-9.jpg)
Example: Words class Words { public static void main (String[] args) { String title; int nbr. Pages; Dictionary webster = new Dictionary ("Webster's"); Book my. Book = new Book ("Java Solutions", 526); Book [] book. Collection = new Book[5]; book. Collection[0] = webster; book. Collection[1] = my. Book; book. Collection[2] = new Dictionary ("Noah's", 948); book. Collection[3] = new Book("Art of Programming", 500); book. Collection[4] = new Book("Science of Programming", 700);

Words: Continued for (int i = 0; i < book. Collection. length; i++) { title = book. Collection[i]. get. Title(); nbr. Pages = book. Collection[i]. page. Message(); System. out. print((i + 1) + ") " + title + " with " + nbr. Pages + " pages. "); if (book. Collection[i] instanceof Dictionary) ((Dictionary) book. Collection[i]). definition. Message(); else System. out. println(""); } } }
![Command Line Arguments public class Command. Line. Arguments { public static void main(String[] args) Command Line Arguments public class Command. Line. Arguments { public static void main(String[] args)](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-11.jpg)
Command Line Arguments public class Command. Line. Arguments { public static void main(String[] args) { int length = args. length; System. out. println("args. length=" + length); for (int i = 0; i < length; i++) { System. out. println("args[" + i + "]=" + args[i]); } } }

Command Line Arguments Output: C: Examples>java Command. Line. Arguments args. length=0 C: Examples>java Command. Line. Arguments Hello World! args. length=2 args[0]=Hello args[1]=World!
![Selection Sort public class Sorts { public static void selection. Sort(int[] numbers) { int Selection Sort public class Sorts { public static void selection. Sort(int[] numbers) { int](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-13.jpg)
Selection Sort public class Sorts { public static void selection. Sort(int[] numbers) { int min, temp; for (int index = 0; index < numbers. length-1; index++) { min = index; for (int scan = index+1; scan < numbers. length; scan++) if (numbers[scan] < numbers[min]) min = scan; // Swap the values temp = numbers[min]; numbers[min] = numbers[index]; numbers[index] = temp; } }
![Example: Sort. Grades. java public class Sort. Grades { public static void main (String[] Example: Sort. Grades. java public class Sort. Grades { public static void main (String[]](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-14.jpg)
Example: Sort. Grades. java public class Sort. Grades { public static void main (String[] args) { int[] grades = {89, 94, 69, 80, 97, 85, 73, 91, 77, 85, 93}; Sorts. selection. Sort(grades); for (int index = 0; index < grades. length; index++) System. out. print (grades[index] + " "); } }
![Sorting Arrays of Objects public class Sorts { public static void insertion. Sort(Comparable[] objects) Sorting Arrays of Objects public class Sorts { public static void insertion. Sort(Comparable[] objects)](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-15.jpg)
Sorting Arrays of Objects public class Sorts { public static void insertion. Sort(Comparable[] objects) { for (int index = 1; index < objects. length; index++) { Comparable key = objects[index]; int position = index; // shift larger values to the right while (position > 0 && objects[position-1]. compare. To(key) > 0) { objects[position] = objects[position-1]; position--; } objects[position] = key; } }

Example: Contact. java class Contact implements Comparable { private String first. Name, last. Name, phone; public Contact(String first. Name, String last. Name, String phone) { this. first. Name = first. Name; this. last. Name = last. Name; this. phone = phone; } public String to. String () { return last. Name + ", " + first. Name + "t" + phone; }

Example: Contact. java public int compare. To (Object other) { int result; if (last. Name. equals(((Contact)other). last. Name)) { result = first. Name. compare. To(((Contact)other). first. Name); } else { result = last. Name. compare. To(((Contact)other). last. Name); } return result; } }

Example: Sort. Phone. List. java public class Sort. Phone. List { public static void main (String[] args) { Contact[] friends = new Contact[7]; friends[0] = new Contact("John", "Smith", "610 -555 -7384"); friends[1] = new Contact(…); friends[2] = new Contact(…); friends[3] = new Contact(…); friends[4] = new Contact(…); friends[5] = new Contact(…); friends[6] = new Contact("Marsha", "Grant", "243 -555 -2837"); Sorts. insertion. Sort(friends); for (int index = 0; index < friends. length; index++) System. out. println (friends[index]); } }

Vector Class A variable-sized list of objects. Methods: n n n void add. Element(Object obj) void insert. Element. At(Object obj, int i) void set. Element. At(Object obj, int i) Object remove(int i) boolean remove. Element(Object obj) void remove. Element. At(int i) void clear() boolean contains(Object obj) int index. Of(Object obj) Object element. At(int i) boolean is. Empty() int size()

Example: Beatles. java import java. util. Vector; public class Beatles { public static void main (String[] args) { Vector band = new Vector(); band. add. Element ("Paul"); band. add. Element ("Pete"); band. add. Element ("John"); band. add. Element ("George"); System. out. println (band); band. remove. Element ("Pete"); System. out. println (band); System. out. println ("At index 1: "+ band. element. At(1)); band. insert. Element. At ("Ringo", 2); System. out. println (band); System. out. println ("Size of the band: " + band. size()); } }
![Example: Beatles. java Output C: Examples>java Beatles [Paul, Pete, John, George] [Paul, John, George] Example: Beatles. java Output C: Examples>java Beatles [Paul, Pete, John, George] [Paul, John, George]](http://slidetodoc.com/presentation_image_h/1246598254b17503b4b71edd10354692/image-21.jpg)
Example: Beatles. java Output C: Examples>java Beatles [Paul, Pete, John, George] [Paul, John, George] At index 1: John [Paul, John, Ringo, George] Size of the band: 4

Applet Class Hierarchy

Applet Methods called by the system public void init() When the applet is first loaded. Do initialization here. public void start() When the applet is displayed. public void stop() When the browser leaves the page containing the applet. public void destroy() public void paint(Graphics g)

GUI – graphical user interface. Users interact with various elements on the screen • The user expresses intent by clicking a mouse or by typing a letter on the keyboard. • The user action is an event

Event an object that represents a user action at the computer’s interface Events can be classified by the action that created them causes -- mouse pressed or key pressed, etc. w Events can also can be generated by other programs. (timer) the source – button, slide-bar, etc. . w Different sources of events are represented by different classes: Mouse. Event, Action. Event, etc.

GUI usage requires handling GUI events n n GUI components are the “source” of events. Small event-handling programs should be constructed to handle specific events. Small programs reduce complexity Programs that handle events from a particular GUI component, should be registered with the source. GUI components maintain a “registration list” of interested listeners When an event occurs at the GUI component, all programs on the “registration list” are given data about the event

Listeners an object that waits for and responses to particular types of events. n n There are different types of listeners represented by different listener interfaces: Mouse. Listener, Action. Listener, etc. A listener class implements one of the listener interfaces.

Delegation Model Has A component that generates events An object that deals with the event. Important features of this model Any component can be the source of an event Any class can be a listener for an event if it implements the appropriate listener interface The event is only sent to listeners that are registered with the source of the event

Events and Listeners Event Source Listener This object may generate an event This object waits for and responds to an event When an event occurs, the generator calls the appropriate method of the listener, passing an object that describes the event

To build a listener that responds to an event, create an object instance of a class that implements the listener interface register the listener to the graphical component that generates the event (typically an add method of the source) when an event occurs at the source, the appropriate method of the listener is called automatically the listener receives an “event object” as a parameter. information in the event object can be used to determine the program’s reaction to the event

Interface Mouse. Listener void mouse. Pressed(Mouse. Event event) void mouse. Released(Mouse. Event event) void mouse. Clicked(Mouse. Event event) void mouse. Entered(Mouse. Event event) void mouse. Exited(Mouse. Event event)

Class Mouse. Event Point get. Point() int get. X() int get. Y() int get. Click. Cont()

Listener: Dots. Mouse. Listener. java import java. applet. Applet; import java. awt. *; import java. awt. event. *; class Dots. Mouse. Listener implements Mouse. Listener { private Dots applet; public Dots. Mouse. Listener(Dots applet) { this. applet = applet; } public void mouse. Clicked(Mouse. Event event) { Point click. Point = event. get. Point(); applet. set. Point (click. Point); applet. repaint(); } public void mouse. Pressed(Mouse. Event event) {} public void mouse. Released(Mouse. Event event) {} public void mouse. Entered(Mouse. Event event) {} public void mouse. Exited(Mouse. Event event) {} }

Example: Dots. java import java. applet. Applet; import java. awt. *; public class Dots extends Applet { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 100; private final int RADIUS = 6; private Point click. Point = null; public void init() { Dots. Mouse. Listener listener = new Dots. Mouse. Listener(this); add. Mouse. Listener(listener); set. Background(Color. black); set. Size(APPLET_WIDTH, APPLET_HEIGHT); }

Dots. java (continued) public void paint(Graphics page) { page. set. Color (Color. green); if (click. Point != null) page. fill. Oval(click. Point. x - RADIUS, click. Point. y - RADIUS, RADIUS * 2, RADIUS * 2); } public void set. Point(Point point) { click. Point = point; } }

Interface Mouse. Motion. Listener void mouse. Moved(Mouse. Event event) void mouse. Dragged(Mouse. Event event)

Example Rubber. Lines. java import java. applet. Applet; import java. awt. *; import java. awt. event. *; public class Rubber. Lines extends Applet implements Mouse. Listener, Mouse. Motion. Listener { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 200; private Point point 1 = null; private Point point 2 = null; public void init() { add. Mouse. Listener(this); add. Mouse. Motion. Listener(this); set. Background(Color. black); set. Size(APPLET_WIDTH, APPLET_HEIGHT); }

Example Rubber. Lines. java public void paint(Graphics page) { page. set. Color (Color. green); if (point 1 != null && point 2 != null) page. draw. Line (point 1. x, point 1. y, point 2. x, point 2. y); } public void mouse. Pressed(Mouse. Event event) { point 1 = event. get. Point(); } public void mouse. Dragged(Mouse. Event event) { point 2 = event. get. Point(); repaint(); }

Example Rubber. Lines. java public void mouse. Clicked(Mouse. Event event) {} public void mouse. Released(Mouse. Event event) {} public void mouse. Entered(Mouse. Event event) {} public void mouse. Exited(Mouse. Event event) {} public void mouse. Moved(Mouse. Event event) {} }

Handling Key Presses Interface Key. Listener n void key. Pressed(Key. Event event) n void key. Released(Key. Event event) n void key. Typed(Key. Event event) Class Key. Event n int get. Key. Code() n constants for all keys

Example: Direction. java import java. applet. *; import java. awt. event. *; public class Direction extends Applet { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 200; private final int JUMP = 5; // increment for image movement private final int IMAGE_SIZE = 31; private Image up, down, right, left, current. Image; private Audio. Clip bonk; private int x, y;

Example: Direction. java public void init() { request. Focus(); // make sure the applet has the keyboard focus add. Key. Listener(new Direction. Key. Listener()); x = y = 0; up = get. Image (get. Code. Base(), "cyan. Up. gif"); down = get. Image (get. Code. Base(), "cyan. Down. gif"); left = get. Image (get. Code. Base(), "cyan. Left. gif"); right = get. Image (get. Code. Base(), "cyan. Right. gif"); current. Image = right; bonk = get. Audio. Clip (get. Code. Base(), "bonk. au"); set. Background (Color. black); set. Size (APPLET_WIDTH, APPLET_HEIGHT); } public void paint (Graphics page) { page. draw. Image (current. Image, x, y, this); }

Example: Direction. java private class Direction. Key. Listener implements Key. Listener { public void key. Pressed (Key. Event event) { switch (event. get. Key. Code()) { case Key. Event. VK_UP: current. Image = up; if (y > 0) y -= JUMP; break; case Key. Event. VK_DOWN: current. Image = down; if (y < APPLET_HEIGHT-IMAGE_SIZE) y += JUMP; break; case Key. Event. VK_LEFT: current. Image = left; if (x > 0) x -= JUMP; break;

Example: Direction. java case Key. Event. VK_RIGHT: current. Image = right; if (x < APPLET_WIDTH-IMAGE_SIZE) x += JUMP; break; default: bonk. play(); } repaint(); } public void key. Typed (Key. Event event) {} public void key. Released (Key. Event event) {} } }

Applet Methods If an applet requires additional data, image or sound files stored on the same host as the applet, the following methods can be used to locate the host. public URL get. Code. Base() Returns URL of the directory that contains the applet’s. class file public URL get. Document. Base() Returns URL of the current HTML document

Loading Audios / Images public Audio. Clip get. Audio. Clip(URL absolute) public Audio. Clip get. Audio. Clip(URL base, String rel) public Image get. Image(URL absolute) public Image get. Image(URL base, String rel)

URL The URL form is: protocol: //host_name/path_name/file_name protocol is the format for transferring files (http, ftp, gopher) host_name is a hierarchical listing of java domains listed in increasing order of generality (java. sun. com, cs. some. edu: 8080 – port number) path_name is a hierarchical listing of the file structure listed in decreasing order of generality (products/jdk/1. 1/docs/api)

Absolute & Relative URLs Absolute URL http: //java. sun. com/products/jdk/1. 1/docs/api/tree. html Relative URL (operates within context of above URL) packages. html (replaces tree. html) foo/hello. html (replaces tree. html) /bar/notes. html (replaces /api/tree. html) If the image named test. gif is contained in the relative URL /images then the following code will load the image URL test. URL = new URL(get. Code. Base(), “/images/test. gif”); Image test. Image = get. Image(test. URL);

URL Class package java. net URL Constructors URL(String name) URL(URL base, String relative) URL(String protocol, String host, String file) URL(String protocol, String host, int port, String file) URL Methods String get. File() String get. Host() int get. Port() String get. Protocol()

Animation An animation is a constantly changing series of pictures or images that create the illusion of movement We can create animations in Java by changing a picture slightly over time The speed of a Java animation is usually controlled by a Timer object Timer class n Timer(int delay, Action. Listener listener) n void add. Action. Listener(Action. Listener listener) n boolean is. Running() n void start() n void stop()

Example: Rebound. java import java. applet. Applet; import java. awt. *; import java. awt. event. *; import javax. swing. Timer; public class Rebound extends Applet { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 100; private final int IMAGE_SIZE = 35; private final int DELAY = 20; private Timer timer; private Image image; private int x, y, move. X, move. Y;

Example: Rebound. java public void init() { add. Mouse. Listener(new Rebound. Mouse. Listener()); timer = new Timer(DELAY, new Rebound. Action. Listener()); timer. start(); x = 0; y = 40; move. X = move. Y = 3; image = get. Image(get. Code. Base(), "happy. Face. gif"); set. Background(Color. black); set. Size(APPLET_WIDTH, APPLET_HEIGHT); } public void paint(Graphics page) { page. draw. Image(image, x, y, this); }

Example: Rebound. java private class Rebound. Mouse. Listener implements Mouse. Listener { public void mouse. Clicked(Mouse. Event event) { if (timer. is. Running()) timer. stop(); else timer. start(); } public void mouse. Entered(Mouse. Event event) {} public void mouse. Exited(Mouse. Event event) {} public void mouse. Pressed(Mouse. Event event) {} public void mouse. Released(Mouse. Event event) {} }

Example: Rebound. java private class Rebound. Action. Listener implements Action. Listener { public void action. Performed(Action. Event event) { x += move. X; y += move. Y; if (x <= 0 || x >= APPLET_WIDTH-IMAGE_SIZE) move. X = move. X * -1; if (y <= 0 || y >= APPLET_HEIGHT-IMAGE_SIZE) move. Y = move. Y * -1; repaint(); } } }
- Slides: 54