Implementing Comparable

Post on 13-Feb-2016

37 views 0 download

description

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; - PowerPoint PPT Presentation

Transcript of Implementing Comparable

Implementing Comparablepublic 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; }}

ArrayAn 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

Array Examplesint[] 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 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,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: GradeRange.javapublic 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]); }}

Example: Wordsclass 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);

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(""); } }}

Command Line Argumentspublic 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]); } }}

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!

Selection Sortpublic 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; } }

Example: SortGrades.javapublic 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] + " "); }}

Sorting Arrays of Objectspublic 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; } }

Example: Contact.javaclass 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; }

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; }}

Example: SortPhoneList.javapublic 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]); }}

Vector ClassA 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()

Example: Beatles.javaimport 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()); }}

Example: Beatles.javaOutputC:\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.

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.

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

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

Delegation ModelHas

A component that generates eventsAn object that deals with the event.

Important features of this modelAny component can be the source of an eventAny class can be a listener for an event if it implements the appropriate listener interfaceThe event is only sent to listeners that are registered with the source of the event

Events and Listeners

Source

This object mayThis object maygenerate an eventgenerate an event

Listener

This object waits for andThis object waits for andresponds to an eventresponds to an event

Event

When an event occurs, the generator callsWhen an event occurs, the generator callsthe appropriate method of the listener,the appropriate method of the listener,

passing an object that describes the eventpassing 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 MouseListenervoid mousePressed(MouseEvent event)

void mouseReleased(MouseEvent event)

void mouseClicked(MouseEvent event)

void mouseEntered(MouseEvent event)

void mouseExited(MouseEvent event)

Class MouseEventPoint getPoint()

int getX()

int getY()

int getClickCont()

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) {}}

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); }

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; }}

Interface MouseMotionListener

void mouseMoved(MouseEvent event)

void mouseDragged(MouseEvent event)

Example RubberLines.javaimport 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); }

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(); }

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) {}}

Handling Key Presses

Interface KeyListener void keyPressed(KeyEvent event) void keyReleased(KeyEvent event) void keyTyped(KeyEvent event)

Class KeyEvent int getKeyCode() constants for all keys

Example: Direction.javaimport 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;

Example: Direction.javapublic 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); }

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;

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) {} }}

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

Loading Audios / Images

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 URLsAbsolute 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);

URL Class package java.net

URL ConstructorsURL(String name) URL(URL base, String relative)URL(String protocol, String host, String file)URL(String protocol, String host, int port, String file)

URL MethodsString getFile() String getHost()int getPort()String getProtocol()

AnimationAn 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()

Example: Rebound.javaimport 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, moveX, moveY;

Example: Rebound.java public void init() { addMouseListener(new ReboundMouseListener()); timer = new Timer(DELAY, new ReboundActionListener()); timer.start(); x = 0; y = 40; moveX = moveY = 3; image = getImage(getCodeBase(), "happyFace.gif"); setBackground(Color.black); setSize(APPLET_WIDTH, APPLET_HEIGHT); } public void paint(Graphics page) { page.drawImage(image, x, y, this); }

Example: Rebound.java private class ReboundMouseListener implements MouseListener { public void mouseClicked(MouseEvent event) { if (timer.isRunning()) timer.stop(); else timer.start(); } public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mousePressed(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} }

Example: Rebound.java private class ReboundActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { x += moveX; y += moveY; if (x <= 0 || x >= APPLET_WIDTH-IMAGE_SIZE) moveX = moveX * -1; if (y <= 0 || y >= APPLET_HEIGHT-IMAGE_SIZE) moveY = moveY * -1; repaint(); } }}