Title: Implementing Comparable
1Implementing 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) lt TOLERANCE)
- result 0
- else if (difference gt 0)
- result 1
- else
- result -1
- return result
-
2Array
- 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
3Array Examples
int ia new int3 ia0 1 ia1 2
ia2 3 //----------------------- int ia
new int3 //----------------------- int ia
1, 2, 3 float mat new float45
for (int y 0 y lt mat.length y) for
(int x 0 x lt maty.length x)
matyx 0.0 // mat.length number of
rows // maty.length number of columns in row y
4Variable length array
int table table new int4
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 lt table.length i) for (int j
0 j lt tablei.length j) if
(tableij gt max) max table ij
54 Dimensional array
int table new int5678 .
. . int a,b,c,d,max 0 for (a 0 a lt
table.length a) for (b 0 b lt
tablea.length b) for (c 0 c lt
tableab.length c) for (d 0 d lt
table abc.length d) if
(tableabcd gt max) max table
abcd
6Arrays 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
7Arrays 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 String25
- The declaration does NOT create the String
objects themselves - Each object stored in an array must be
instantiated separately
8Example 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 lt cutoff.length level)
System.out.println (gradeslevel "\t"
cutofflevel)
9Example 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 Book5
- bookCollection0 webster
- bookCollection1 myBook
- bookCollection2 new Dictionary ("Noah's",
948) - bookCollection3 new Book("Art of
Programming", 500) - bookCollection4 new Book("Science of
Programming", 700)
10Words Continued
-
- for (int i 0 i lt bookCollection.length i)
- title bookCollectioni.getTitle()
- nbrPages bookCollectioni.pageMessage()
- System.out.print((i 1) ") " title
- " with " nbrPages " pages.")
- if (bookCollectioni instanceof Dictionary)
- ((Dictionary) bookCollectioni).definitionM
essage() - else
- System.out.println("")
-
-
-
11Command Line Arguments
public class CommandLineArguments public
static void main(String args) int length
args.length System.out.println("args.lengt
h" length) for (int i 0 i lt length
i) System.out.println("args" i
"" argsi)
12Command Line ArgumentsOutput
C\Examplesgtjava CommandLineArguments
args.length0 C\Examplesgtjava
CommandLineArguments Hello World! args.length2
args0Hello args1World!
13Selection Sort
public class Sorts public static void
selectionSort(int numbers) int min,
temp for (int index 0 index lt
numbers.length-1 index) min
index for (int scan index1 scan lt
numbers.length scan) if
(numbersscan lt numbersmin) min
scan // Swap the values temp
numbersmin numbersmin
numbersindex numbersindex temp
14Example 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 lt grades.length
index) System.out.print (gradesindex
" ")
15Sorting Arrays of Objects
public class Sorts public static void
insertionSort(Comparable objects) for
(int index 1 index lt objects.length
index) Comparable key
objectsindex int position index
// shift larger values to the right while
(position gt 0 objectsposition-1
.compareTo(key) gt 0) objectsposition
objectsposition-1 position--
objectsposition key
16Example 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
17Example Contact.java
public int compareTo (Object other) int
result if (lastName.equals(((Contact)other).l
astName)) result
firstName.compareTo(((Contact)other).firstName)
else result
lastName.compareTo(((Contact)other).lastName)
return result
18Example SortPhoneList.java
public class SortPhoneList public static void
main (String args) Contact friends
new Contact7 friends0 new
Contact("John", "Smith", "610-555-7384")
friends1 new Contact() friends2 new
Contact() friends3 new Contact()
friends4 new Contact() friends5 new
Contact() friends6 new
Contact("Marsha", "Grant", "243-555-2837")
Sorts.insertionSort(friends) for (int index
0 index lt friends.length index)
System.out.println (friendsindex)
19Vector 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()
20Example 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())
21Example Beatles.javaOutput
C\Examplesgtjava Beatles Paul, Pete, John,
George Paul, John, George At index 1
John Paul, John, Ringo, George Size of the
band 4
22Applet Class Hierarchy
23Applet 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)
24GUI 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
25Event
- an object that represents a user action at the
computers 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.
26GUI 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
27Listeners
- 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.
28Delegation 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
29Events and Listeners
When an event occurs, the generator calls the
appropriate method of the listener, passing an
object that describes the event
30To 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 programs reaction to the event
31Interface MouseListener
- void mousePressed(MouseEvent event)
- void mouseReleased(MouseEvent event)
- void mouseClicked(MouseEvent event)
- void mouseEntered(MouseEvent event)
- void mouseExited(MouseEvent event)
32Class MouseEvent
- Point getPoint()
- int getX()
- int getY()
- int getClickCont()
33Listener DotsMouseListener.java
import java.applet.Applet import
java.awt. import java.awt.event. class
DotsMouseListener implements MouseListener
private Dots applet public DotsMouseListener(Do
ts 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)
34Example 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(list
ener) setBackground(Color.black)
setSize(APPLET_WIDTH, APPLET_HEIGHT)
35Dots.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
36Interface MouseMotionListener
- void mouseMoved(MouseEvent event)
- void mouseDragged(MouseEvent event)
37Example 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)
38Example 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()
39Example 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)
40Handling Key Presses
- Interface KeyListener
- void keyPressed(KeyEvent event)
- void keyReleased(KeyEvent event)
- void keyTyped(KeyEvent event)
- Class KeyEvent
- int getKeyCode()
- constants for all keys
41Example 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
42Example 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)
43Example Direction.java
private class DirectionKeyListener
implements KeyListener public void
keyPressed (KeyEvent event) switch
(event.getKeyCode()) case
KeyEvent.VK_UP currentImage up
if (y gt 0) y - JUMP break case
KeyEvent.VK_DOWN currentImage down
if (y lt APPLET_HEIGHT-IMAGE_SIZE)
y JUMP break case
KeyEvent.VK_LEFT currentImage left
if (x gt 0) x - JUMP break
44Example Direction.java
case KeyEvent.VK_RIGHT
currentImage right if (x lt
APPLET_WIDTH-IMAGE_SIZE) x JUMP
break default bonk.play()
repaint() public void
keyTyped (KeyEvent event) public void
keyReleased (KeyEvent event)
45Applet 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
applets .class file - public URL getDocumentBase()
- Returns URL of the current HTML document
-
46Loading 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)
47URL
- 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.edu8080 port number) -
- path_name is a hierarchical listing of the file
structure listed in decreasing order of
generality (products/jdk/1.1/docs/api) -
48Absolute Relative URLs
- Absolute URL
- http//java.sun.com/products/jdk/1.1/docs/api/tr
ee.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)
-
49URL 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()
50Animation
- 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()
51Example 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, moveX, moveY
52Example 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)
53Example 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)
54Example Rebound.java
private class ReboundActionListener
implements ActionListener public void
actionPerformed(ActionEvent event) x
moveX y moveY if (x lt 0 x gt
APPLET_WIDTH-IMAGE_SIZE) moveX moveX
-1 if (y lt 0 y gt APPLET_HEIGHT-IMAGE_S
IZE) moveY moveY -1
repaint()