1 / 54

Implementing Comparable

Implementing Comparable. public class Rational implements Comparable { public int compareTo (Object obj) { final double TOLERANCE = .0001; Rational other = (Rational ) obj; double otherRational = (double) other. numerator/ other. denominator;

gloria
Télécharger la présentation

Implementing Comparable

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

E N D

Presentation Transcript


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

  2. Array • An ordered list of values of the same type. • That type can be primitive or • 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

  3. 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

  4. 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];

  5. 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];

  6. 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

  7. 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

  8. Example: GradeRange.java public class GradeRange { public static void main (String[] args) { String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "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]); } }

  9. Example: Words class Words { public static void main (String[] args) { String title; int nbrPages; Dictionary webster = new Dictionary ("Webster's"); Book myBook = new Book ("Java Solutions", 526); Book [] bookCollection = new Book[5]; bookCollection[0] = webster; bookCollection[1] = myBook; bookCollection[2] = new Dictionary ("Noah's", 948); bookCollection[3] = new Book("Art of Programming", 500); bookCollection[4] = new Book("Science of Programming", 700);

  10. Words: Continued for (int i = 0; i < bookCollection.length; i++) { title = bookCollection[i].getTitle(); nbrPages = bookCollection[i].pageMessage(); System.out.print((i + 1) + ") " + title + " with " + nbrPages + " pages."); if (bookCollection[i] instanceof Dictionary) ((Dictionary) bookCollection[i]).definitionMessage(); else System.out.println(""); } } }

  11. Command Line Arguments public class CommandLineArguments { 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]); } } }

  12. Command Line ArgumentsOutput: C:\Examples>java CommandLineArguments args.length=0 C:\Examples>java CommandLineArguments Hello World! args.length=2 args[0]=Hello args[1]=World!

  13. Selection Sort public class Sorts { public static void selectionSort(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; } }

  14. Example: SortGrades.java public class SortGrades { public static void main (String[] args) { int[] grades = {89, 94, 69, 80, 97, 85, 73, 91, 77, 85, 93}; Sorts.selectionSort(grades); for (int index = 0; index < grades.length; index++) System.out.print (grades[index] + " "); } }

  15. Sorting Arrays of Objects public class Sorts { public static void insertionSort(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].compareTo(key) > 0) { objects[position] = objects[position-1]; position--; } objects[position] = key; } }

  16. Example: Contact.java class Contact implements Comparable { private String firstName, lastName, phone; public Contact(String firstName, String lastName, String phone) { this.firstName = firstName; this.lastName = lastName; this.phone = phone; } public String toString () { return lastName + ", " + firstName + "\t" + phone; }

  17. Example: Contact.java public int compareTo (Object other) { int result; if (lastName.equals(((Contact)other).lastName)) { result = firstName.compareTo(((Contact)other).firstName); } else { result = lastName.compareTo(((Contact)other).lastName); } return result; } }

  18. Example: SortPhoneList.java public class SortPhoneList { 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.insertionSort(friends); for (int index = 0; index < friends.length; index++) System.out.println (friends[index]); } }

  19. Vector Class • A variable-sized list of objects. • Methods: • void addElement(Object obj) • void insertElementAt(Object obj, int i) • void setElementAt(Object obj, int i) • Object remove(int i) • boolean removeElement(Object obj) • void removeElementAt(int i) • void clear() • boolean contains(Object obj) • int indexOf(Object obj) • Object elementAt(int i) • boolean isEmpty() • int size()

  20. Example: Beatles.java import java.util.Vector; public class Beatles { public static void main (String[] args) { Vector band = new Vector(); band.addElement ("Paul"); band.addElement ("Pete"); band.addElement ("John"); band.addElement ("George"); System.out.println (band); band.removeElement ("Pete"); System.out.println (band); System.out.println ("At index 1: "+ band.elementAt(1)); band.insertElementAt ("Ringo", 2); System.out.println (band); System.out.println ("Size of the band: " + band.size()); } }

  21. Example: Beatles.javaOutput C:\Examples>java Beatles [Paul, Pete, John, George] [Paul, John, George] At index 1: John [Paul, John, Ringo, George] Size of the band: 4

  22. Applet Class Hierarchy

  23. 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)

  24. 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

  25. 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. • Events can also can be generated by other programs. (timer) • the source – button, slide-bar, etc.. • Different sources of events are represented by different classes: MouseEvent, ActionEvent, etc.

  26. GUI usage requires handling GUI events • 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

  27. Listeners • an object that waits for and responses to particular types of events. • There are different types of listeners represented by different listener interfaces:MouseListener, ActionListener, etc. • A listener class implements one of the listener interfaces.

  28. 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

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

  30. 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

  31. Interface MouseListener • void mousePressed(MouseEvent event) • void mouseReleased(MouseEvent event) • void mouseClicked(MouseEvent event) • void mouseEntered(MouseEvent event) • void mouseExited(MouseEvent event)

  32. Class MouseEvent • Point getPoint() • int getX() • int getY() • int getClickCont()

  33. Listener: DotsMouseListener.java import java.applet.Applet; import java.awt.*; import java.awt.event.*; class DotsMouseListener implements MouseListener { private Dots applet; public DotsMouseListener(Dots applet) { this.applet = applet; } public void mouseClicked(MouseEvent event) { Point clickPoint = event.getPoint(); applet.setPoint (clickPoint); applet.repaint(); } public void mousePressed(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} }

  34. 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 clickPoint = null; public void init() { DotsMouseListener listener = new DotsMouseListener(this); addMouseListener(listener); setBackground(Color.black); setSize(APPLET_WIDTH, APPLET_HEIGHT); }

  35. Dots.java (continued) public void paint(Graphics page) { page.setColor (Color.green); if (clickPoint != null) page.fillOval(clickPoint.x - RADIUS, clickPoint.y - RADIUS, RADIUS * 2, RADIUS * 2); } public void setPoint(Point point) { clickPoint = point; } }

  36. Interface MouseMotionListener • void mouseMoved(MouseEvent event) • void mouseDragged(MouseEvent event)

  37. Example RubberLines.java import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class RubberLines extends Applet implements MouseListener, MouseMotionListener { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 200; private Point point1 = null; private Point point2 = null; public void init() { addMouseListener(this); addMouseMotionListener(this); setBackground(Color.black); setSize(APPLET_WIDTH, APPLET_HEIGHT); }

  38. Example RubberLines.java public void paint(Graphics page) { page.setColor (Color.green); if (point1 != null && point2 != null) page.drawLine (point1.x, point1.y, point2.x, point2.y); } public void mousePressed(MouseEvent event) { point1 = event.getPoint(); } public void mouseDragged(MouseEvent event) { point2 = event.getPoint(); repaint(); }

  39. Example RubberLines.java public void mouseClicked(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mouseMoved(MouseEvent event) {} }

  40. Handling Key Presses • Interface KeyListener • void keyPressed(KeyEvent event) • void keyReleased(KeyEvent event) • void keyTyped(KeyEvent event) • ClassKeyEvent • int getKeyCode() • constants for all keys

  41. Example: Direction.java import java.applet.*; import java.awt.*; 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, currentImage; private AudioClip bonk; private int x, y;

  42. Example: Direction.java public void init() { requestFocus(); // make sure the applet has the keyboard focus addKeyListener(new DirectionKeyListener()); x = y = 0; up = getImage (getCodeBase(), "cyanUp.gif"); down = getImage (getCodeBase(), "cyanDown.gif"); left = getImage (getCodeBase(), "cyanLeft.gif"); right = getImage (getCodeBase(), "cyanRight.gif"); currentImage = right; bonk = getAudioClip (getCodeBase(), "bonk.au"); setBackground (Color.black); setSize (APPLET_WIDTH, APPLET_HEIGHT); } public void paint (Graphics page) { page.drawImage (currentImage, x, y, this); }

  43. Example: Direction.java private class DirectionKeyListener implements KeyListener { public void keyPressed (KeyEvent event) { switch (event.getKeyCode()) { case KeyEvent.VK_UP: currentImage = up; if (y > 0) y -= JUMP; break; case KeyEvent.VK_DOWN: currentImage = down; if (y < APPLET_HEIGHT-IMAGE_SIZE) y += JUMP; break; case KeyEvent.VK_LEFT: currentImage = left; if (x > 0) x -= JUMP; break;

  44. Example: Direction.java case KeyEvent.VK_RIGHT: currentImage = right; if (x < APPLET_WIDTH-IMAGE_SIZE) x += JUMP; break; default: bonk.play(); } repaint(); } public void keyTyped (KeyEvent event) {} public void keyReleased (KeyEvent event) {} } }

  45. 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 getCodeBase() Returns URL of the directory that contains the applet’s .class file • public URL getDocumentBase() Returns URL of the current HTML document

  46. Loading Audios / Images • public AudioClip getAudioClip(URL absolute) • public AudioClip getAudioClip(URL base,String rel) • public Image getImage(URL absolute) • public Image getImage(URL base,String rel)

  47. 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)

  48. 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 testURL = new URL(getCodeBase(), “/images/test.gif”); Image testImage = getImage(testURL);

  49. 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 getFile() String getHost() int getPort() String getProtocol()

  50. 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 • Timer(int delay, ActionListener listener) • void addActionListener(ActionListener listener) • boolean isRunning() • void start() • void stop()

More Related