Arrays and loops - PowerPoint PPT Presentation

1 / 189
About This Presentation
Title:

Arrays and loops

Description:

when you are looking for a particular element (e.g. biggest or smallest) ... findDog({'mouse', 'lizard','snake'}) false. findDog({'beetle','hamster'}) false ... – PowerPoint PPT presentation

Number of Views:286
Avg rating:3.0/5.0
Slides: 190
Provided by: paulc1
Category:
Tags: arrays | lizard | loops

less

Transcript and Presenter's Notes

Title: Arrays and loops


1
Arrays and loops
  • Often, you need a loop to visit all the elements
    in the array
  • when you are looking for a particular element
    (e.g. biggest or smallest)
  • you want to find a total of all the elements
  • you want to count the elements

2
Problem write a method will return true if one
of the pets is a dog
  • findDog("fish", "cat","rat","dog") ? true
  • findDog("mouse", "lizard","snake") ? false
  • findDog("beetle","hamster") ? false
  • findDog() ? false (empty array)

3
Problem write a method will return true if one
of the pets is a dog
  • boolean findDog(String pets)
  • ??

4
Problem write a method will return true if one
of the pets is a dog
  • boolean findDog(String pets)
  • ??
  • return true
  • ??
  • return false

5
Problem write a method will return true if one
of the pets is a dog
  • boolean findDog(String pets)
  • if( ?? )
  • return true
  • ??
  • return false

6
Problem write a method will return true if one
of the pets is a dog
  • boolean findDog(String pets)
  • if( pets ?? "dog" )
  • return true
  • ??
  • return false

7
Problem write a method will return true if one
of the pets is a dog
  • boolean findDog(String pets)
  • if(pets??.equals("dog"))
  • return true
  • ??
  • return false

8
Problem write a method will return true if one
of the pets is a dog
  • boolean findDog(String pets)
  • for( ?? ?? ?? )
  • if(pets??.equals("dog"))
  • return true
  • ??
  • return false

9
Problem write a method will return true if one
of the pets is a dog
  • boolean findDog(String pets)
  • for( int nI 0 ?? ?? )
  • if(petsnI.equals("dog"))
  • return true
  • ??
  • return false

10
Problem write a method will return true if one
of the pets is a dog
  • boolean findDog(String pets)
  • for( int nI 0 nI ltpets.lengthnI)
  • if(petsnI.equals("dog"))
  • return true
  • ??
  • return false

11
else doesn't work here!!
  • boolean findDog(String pets)
  • for( int nI 0 nI ltpets.lengthnI)
  • if(petsnI.equals("dog"))
  • return true
  • else ??
  • return false

12
else doesn't work here!!
  • boolean findDog(String pets)
  • for( int nI 0 nI ltpets.lengthnI)
  • if(petsnI.equals("dog"))
  • return true
  • else ??
  • return false

13
now it works !!
  • boolean findDog(String pets)
  • for( int nI 0 nI ltpets.lengthnI)
  • if(petsnI.equals("dog"))
  • return true
  • return false

14
Problem write a method will count the pets that
are dogs OR cats
  • countDogsCats("fish", "cat","rat","dog") ? 2
  • countDogsCats("mouse", "lizard","snake") ? 0
  • countDogsCats("beetle","hamster") ? 0
  • countDogsCats() ? 0 (empty array)

15
Problem write a method will count the pets that
are dogs OR cats
  • int countDogsCats(String pets)
  • ??

16
Problem write a method will count the pets that
are dogs OR cats
  • int countDogsCats(String pets)
  • int nCount 0
  • ??
  • return nCount

17
Problem write a method will count the pets that
are dogs OR cats
  • int countDogsCats(String pets)
  • int nCount 0
  • for(int nI0nIltpets.lengthnI)
  • if(petsnI.equals("dog")
  • petsnI.equals("cat") )
  • nCount
  • return nCount

18
Problem write a method will return true if one
of the FIRST 3 pets is a dog
  • findDogIn3("fish", "cat","rat","dog") ? false
  • findDogIn3("mouse", "lizard","snake") ? false
  • findDogIn3("beetle","hamster") ? false
  • findDogIn3() ? false (empty array)

19
Problem write a method will return true if one
of the FIRST 3 pets is a dog
  • boolean findDogIn3(String pets)
  • ??

20
Problem write a method will return true if one
of the FIRST 3 pets is a dog
  • boolean findDogIn3(String pets)
  • for( int nI 0 nI lt??nI)
  • if(petsnI.equals("dog"))
  • return true
  • return false

21
Problem write a method will return true if one
of the FIRST 3 pets is a dog
  • boolean findDogIn3(String pets)
  • int nEnd
  • ??
  • for( int nI 0 nI ltnEndnI)
  • if(petsnI.equals("dog"))
  • return true
  • return false

22
Problem write a method will return true if one
of the FIRST 3 pets is a dog
  • boolean findDogIn3(String pets)
  • int nEnd
  • if(pets.length gt 3)
  • nEnd 3
  • else
  • nEnd pets.length
  • for( int nI 0 nI ltnEndnI)
  • if(petsnI.equals("dog"))
  • return true
  • return false

23
Problem write a method will return true if one
of the FIRST 3 pets is a dog
  • boolean findDogIn3(String pets)
  • for( int nI 0 nIlt3 nIltpets.lengthnI)
  • if(petsnI.equals("dog"))
  • return true
  • return false

24
Javabat Warmup2 gt arrayFront9
  • http//www.javabat.com/prob?idWarmup2.arrayFront9
  • Given an array of ints, return true if one of the
    first 4 elements in the array is a 9. The array
    length may be less than 4.
  • arrayFront9(1, 2, 9, 3, 4) ? true
  • arrayFront9(1, 2, 3, 4, 9) ? false
  • arrayFront9(1, 2, 3, 4, 5) ? false

25
Javabat Warmup2 gt arrayCount9
  • http//www.javabat.com/prob?idWarmup2.arrayCount9
  • Given an array of ints, return the number of 9's
    in the array.
  • arrayCount9(1, 2, 9) ? 1
  • arrayCount9(1, 9, 9) ? 2
  • arrayCount9(1, 9, 9, 3, 9) ? 3

26
Javabat Array2 gt has22
  • http//www.javabat.com/prob?idArray2.has22
  • Given an array of ints, return true if the array
    contains a 2 next to a 2 somewhere.
  • has22(1, 2, 2) ? true
  • has22(1, 2, 1, 2) ? false
  • has22(2, 1, 2) ? false

27
Interfaces
  • public class Example extends Applet implements
    ActionListener
  • When you use implements you are using
    (implementing) an interface
  • So what's an interface?

28
Interfaces
  • An interface is like a class, but simpler
  • An interface is just a list of methods
  • When you implement an interface, you must write
    the methods that are listed in that interface

29
Interfaces
  • public class Example extends Applet implements
    ActionListener
  • To implement an ActionListener we must write the
    following method
  • public void actionPerformed(ActionEvent e)
  • We're not limited to that one method, we can
    write any others we want to

30
Interfaces
  • An interface says All classes that implement
    this interface will be able to do these things
  • You can think of interfaces this way
  • I (Mr. Simon) implement the Teacher interface
  • You implement the Student interface

31
Interfaces
  • Inside of the Teacher interface there should be
    teach and grade methodsso if you want to be a
    teacher you have to be able to teach and grade
  • Inside of the Student interface there should be
    study, listen and learn methodsso if you want to
    be a student you have to be able to study, listen
    and learn

32
Problem Create a SuperHero interface
  • interface SuperHero
  • public void fight()
  • public void specialPower()

33
Problem Create a SuperHero interface
  • In designing a SuperHero interface, we are
    setting the standards for what all SuperHeroes
    must do
  • They are not limited to the methods in the
    interface--there can be additional methods as well

34
Problem Create a SuperHero interface
  • class Spiderman implements SuperHero
  • public void fight()
  • System.out.println
  • ("I will spin a web to trap you!")
  • public void specialPower()
  • System.out.println
  • ("I can swing through the city streets.")
  • public void spiderSense()
  • System.out.println
  • ("Hmmm, something's not right")

35
Problem Create a SuperHero interface
  • class Superman implements SuperHero
  • public void fight()
  • System.out.println
  • ("My great strength will defeat you!")
  • public void specialPower()
  • System.out.println("I have Xray vision.")
  • public void kryptonite()
  • System.out.println("Oh no!")

36
Problem Create a SuperHero interface
  • public class InterfaceDemo extends Applet
  • Superman ClarkKent new Superman()
  • Spiderman PeterParker new Spiderman()
  • public void paint(Graphics g)
  • ClarkKent.fight()
  • PeterParker.fight()
  • ClarkKent.specialPower()
  • PeterParker.specialPower()
  • ClarkKent.kryptonite()
  • PeterParker.spiderSense()
  • / Sample Output
  • My great strength will defeat you!
  • I will spin a web to trap you!
  • I have Xray vision.
  • I can swing through the city streets.

37
All SuperHeros can be treated the same and
grouped together
  • public class InterfaceDemo extends Applet
  • Superhero theGoodGuys new Superhero2
  • public void paint(Graphics g)
  • theGoodGuys0 new Superman()
  • theGoodGuys1 new Spiderman()
  • for(int nI 0 nI lt 2 nI)
  • theGoodGuysnI.fight()
  • theGoodGuysnI.specialPower()
  • / Sample Output
  • My great strength will defeat you!
  • I have Xray vision.
  • I will spin a web to trap you!
  • I can swing through the city streets.

38
The keyListener interface
  • Allows your applet to respond to key events
  • interface keyListener
  • public void keyTyped(KeyEvent ke)
  • public void keyPressed(KeyEvent ke)
  • public void keyReleased(KeyEvent ke)
  • Note You don't have to write this, it's included
    in your program with import.java.awt.event.

39
Keyboard Events
  • Every time you press (or release) a key it
    generates an Event
  • We can have our Applet listen for key events by
    making it a KeyListener
  • The KeyListener interface requires three methods
    keyTyped, keyPressed and keyReleased

40
  • public class KeyDemo extends Applet
  • implements
    KeyListener
  • char cChar
  • public void init()
  • addKeyListener(this)
  • public void paint(Graphics g)
  • g.drawString("You pressed " cChar, 20, 20)
  • public void keyTyped(KeyEvent ke)
  • cChar ke.getKeyChar()
  • repaint()
  • public void keyPressed (KeyEvent ke) //not
    used
  • public void keyReleased (KeyEvent ke) //not
    used

41
requestFocus()
  • Our applet is one of many programs running
    simultaneously
  • When you type, how does Windows know where the
    typing should go? Should it go in the URL field
    of the browser, or name a folder or where?
  • One way to tell Windows is to click on the thing
    before you start typing
  • The other is requestFocus()

42
A simple Applet that listens for key events
  • import java.awt.
  • import java.awt.event.
  • import java.applet.
  • public class KeyDemo
  • extends Applet implements KeyListener
  • char cKey
  • public void init()
  • addKeyListener(this)
  • public void paint(Graphics g)
  • g.drawString("The " cKey
  • " key was pressed", 50, 60 )
  • public void keyTyped(KeyEvent ke)
  • cKey ke.getKeyChar()
  • System.out.println(cKey)
  • repaint()

43
Javabat Array2 gt has77
  • http//www.javabat.com/prob?idArray2.has77
  • Given an array of ints, return true if the array
    contains two 7's next to each other, or there are
    two 7's separated by one element, such as with
    7, 1, 7.
  • has77(1, 7, 7) ? true
  • has77(1, 7, 1, 7) ? true
  • has77(1, 7, 1, 1, 7) ? false

44
handles, aliases and Binky
  • Pointer Fun is a 3 minute video from the computer
    science dept. at Stanford
  • In Java, we don't use the word pointer, we use
    handle instead
  • An alias is where two handles refer to the same
    mailbox

45
  • //The code from the Binky video
  • class IntObj
  • int value
  • IntObj x // Allocate the pointers x and y
  • IntObj y // (but not the IntObj pointees)
  • x new IntObj() // Allocate an IntObj pointee
  • // and set x to point to it
  • x.value 42 // Dereference x to store 42
    in its
  • //pointee
  • y.value 13// CRASH -- y does not have a
    pointee yet
  • y x // Pointer assignment sets y to point to
    x's

46
  • IntObj x
  • IntObj y

x
y
47
  • x new IntObj()

x
y
48
  • x.value 42

42
x
y
49
  • y.value 13

42
x
y
50
  • y.value 13
  • //Null Pointer exception

42
x
y
CRASH!
51
  • y x

42
x
y
52
  • y.value 13

13
x
y
53
  • //What would
  • System.out.println(x.value)
  • //Display?

13
x
y
54
  • //Answer 13

13
x
y
55
  • /Practice Quiz Question write some Java code
    that will produce the following structure /

1
x
2
y
56
Why dot equals is generally preferred to
double equals for comparing objects
  • assigns two handles
  • to the same object
  • if( x y)asks
  • Are x and y referring
  • to the same object?
  • if( x.equals(y))asks
  • Do x and y have the same value?

57
X Y refer to the same object
2
x
y
58
X Y have the same value
2
x
2
y
59
Practice Quiz Question What is the output of
this applet?
  • import java.awt.
  • import java.applet.
  • class SomeType
  • String sMessage
  • SomeType(String sText)
  • sMessage sText
  • public class AliasDemo extends Applet
  • SomeType one new SomeType("one")
  • SomeType two new SomeType("two")
  • public void paint(Graphics g)
  • SomeType three two

60
  • SomeType one new SomeType("one")
  • SomeType two new SomeType("two")

one
one
two
two
61
  • SomeType three two
  • three.sMessage new String("three)
  • System.out.println(one.sMessage
  • ", " two.sMessage)

one
one
three
two
three
62
  • three one
  • three.sMessage new String("four)
  • System.out.println(one.sMessage
  • ", " two.sMessage)

four
one
three
two
three
63
final and static
  • In C, you made constants like this
  • const double dCM_IN_INCH 2.54
  • In Java, they look like this
  • final static double dCM_IN_INCH 2.54
  • final works like const, it "locks" the "mailbox"
  • static means there is only one "mailbox" for the
    entire class

64
  • public class StaticDemo extends Applet
  • Student student1 new Student("Bob")
  • Student student2 new Student("Hannah")
  • public void paint(Graphics g)
  • System.out.println(student1.sName)
  • System.out.println(student2.sName)
  • student1.sSchool "Lincoln"
  • System.out.println(student1.sSchool)
  • System.out.println(student2.sSchool)

class Student String sName static String
sSchool "Lowell" Student(String
sWho) sName sWho
/ Sample Output Bob Hannah Lincoln Lincoln Exit
code 0 No Errors /
65
final and static
Bob
student1
Lowell
Hannah
student2
System.out.println(student1.sName) System.out.pri
ntln(student2.sName)
66
final and static
Bob
student1
Lowell
Hannah
student2
student1.sSchool "Lincoln"
67
final and static
Bob
student1
Lincoln
Hannah
student2
student1.sSchool "Lincoln"
68
final and static
Bob
student1
Lincoln
Hannah
student2
System.out.println(student1.sSchool) System.out.p
rintln(student2.sSchool)
69
Three references to the same "mailbox"
Bob
student1
Lincoln
Hannah
student2
student1.sSchool student2.sSchool Student.sSchool

70
Overriding update()
  • Normally, every time we repaint(), the screen is
    completely erased first
  • "Behind the scenes", repaint() calls the method
    update() which erases the screen and then calls
    our paint() method
  • For the etch a sketch assignment, we don't want
    the screen erased, so we will write a new version
    of update()
  • This is called "overriding update()"

71
Overriding update()
  • public void update(Graphics g)
  • paint(g)

72
Symmetrical reflections (mirrors)
(50,30)
480
640
73
Symmetrical reflections (mirrors)
(50,30)
50
480
640
74
Symmetrical reflections (mirrors)
(50,30)
50
50
480
640
75
Symmetrical reflections (mirrors)
(50,30)
(640-50,30)
50
50
480
640
76
panels
  • Sometimes you want part of your applet to use one
    layout and the rest of the applet to use a
    different layout
  • For instance you might want a grid of buttons for
    part of the applet, but with a few extra buttons
    that aren't part of the grid

77
panels
  • You can think of a panel as an "Applet within an
    Applet"
  • Panel buttonPanel new Panel()
  • add(buttonPanel)
  • buttonPanel.setLayout(new GridLayout
  • (nNUM_ROWS, nNUM_COLUMNS, 0, 0))
  • Once you have the panel, you can add buttons to
    it pretty much like you would an applet
  • buttonPanel.add(buttonArraynNum)

78
panels
  • Panel aPanel
  • public void init()
  • aPanel new Panel()
  • add(aPanel)
  • aPanel.setLayout(new BorderLayout())
  • aPanel.add(new Button("North"),BorderLayout.NOR
    TH)
  • aPanel.add(new Button("South"),BorderLayout.SOU
    TH)
  • aPanel.add(new Button("East"),BorderLayout.EAST
    )
  • aPanel.add(new Button("West"),BorderLayout.WEST
    )
  • aPanel.add(new Button("Center"),BorderLayout.CE
    NTER)

79
Message Boxes
  • You know those annoying Message Boxes that pop up
    on some websites saying your computer is infected
    with spyware?
  • Here's how to make them )

80
Message Boxes
  • import java.awt.
  • import java.applet.
  • import javax.swing.
  • public class MessageBoxDemo extends Applet
  • public void init()
  • JOptionPane.showMessageDialog(
  • null,"Some Annoying Message")

81
Input Dialog Box
  • import java.awt.
  • import java.applet.
  • import javax.swing.
  • public class MessageBoxDemo extends Applet
  • String sInput
  • public void init()
  • sInputJOptionPane.showInputDialog(
  • "Type
    Something!")
  • public void paint(Graphics g)
  • g.drawString("You typed " sInput,20,20)

82
Converting to an int
  • import java.awt.
  • import java.applet.
  • import javax.swing.
  • public class MessageBoxDemo extends Applet
  • String sInput
  • int nNum
  • public void init()
  • sInputJOptionPane.showInputDialog("Type an
    Integer")
  • nNum Integer.parseInt(sInput)
  • public void paint(Graphics g)
  • g.drawString("You typed " nNum,20,20)

83
boolean
  • A boolean is a primitive data type that can only
    hold one of two values true or false
  • You can use a boolean anywhere that can use a
    true or false
  • boolean bBool true
  • boolean bValue (nNum gt 0)
  • System.out.println(bValue)
  • if(bValue)
  • System.out.println("positive")

84
boolean methods
  • A boolean method returns true or false
  • boolean isOldEnough(int nAge)
  • if(nAge gt 18)
  • return true
  • else
  • return false

85
boolean methods
  • Here is a shorter version that does the same
    thing
  • boolean isOldEnough(int nAge)
  • return (nAge gt 18)

86
  • public class MysteryBoolean extends Applet
  • FurBall Fred
  • FurBall Murray
  • public void init()
  • Fred new FurBall(Color.red,20)
  • Murray new FurBall(Color.green,25)
  • public void paint(Graphics g)
  • System.out.println(Fred.isBig())
  • System.out.println(Murray.isBig())
  • System.out.println(Fred.isBigAndGreen())
  • System.out.println(Murray.isBigAndGreen())
  • class FurBall

87
Exceptions
  • An exception is a problem that Java doesn't know
    how to deal with
  • new Color(256,-1,100)
  • Exception occurred during event dispatching
  • java.lang.IllegalArgumentException Color
    parameter outside of expected range Red Green

88
More examples of Exceptions
  • int naArray1,2,3
  • naArray30
  • //java.lang.ArrayIndexOutOfBoundsException
  • Button aButton
  • aButton.setBounds(3,4,5,6)
  • //java.lang.NullPointerException
  • System.out.println(5/0)
  • //java.lang.ArithmeticException / by zero

89
What happens if you press the wrong button?
  • Button press new Button("5")
  • Button dont new Button("DO NOT PRESS THIS
    BUTTON!")
  • int nNum 0
  • public void init()
  • add(press)
  • add(dont)
  • press.addActionListener(this)
  • dont.addActionListener(this)
  • public void paint(Graphics g)
  • g.drawString("Number is " nNum, 20, 50)
  • public void actionPerformed(ActionEvent ae)
  • nNum Integer.parseInt(ae.getActionCommand())
  • repaint()

90
Exception handling try catch
  • Exception handling can be used to "bulletproof"
    your code
  • Even if the user does the wrong thing, your
    program won't crash
  • try
  • //code that may cause problem
  • catch (Exception e)
  • //"catch" the problem

91
Exception handling try catch
  • public void actionPerformed(ActionEvent ae)
  • try
  • nNum Integer.parseInt(ae.getActionCommand())
  • catch(Exception e)
  • nNum -9999999999999999
  • System.out.println("Follow directions!")
  • repaint()

92
We can set up multiple catch blocks to handle
different kinds of exceptions
  • Button b1 new Button('x')
  • Button b2
  • . . . .
  • public void actionPerformed(ActionEvent ae)
  • try
  • nNum Integer.parseInt(ae.getActionCommand())
  • catch(NumberFormatException e)
  • System.out.println("Not a number")
  • catch(NullPointerException e)
  • System.out.println("Button doesn't exist")
  • catch(Exception e)
  • System.out.println("Some Other problem")

93
Practice Quiz Question What is the output of
this code fragment?
  • int nTotal 0
  • String sMessages new String4
  • sMessages0 new String("13")
  • sMessages2 new String("abc")
  • sMessages3 new String("7")
  • for(int nI 0 nI lt 5 nI)
  • try
  • if(sMessagesnI.equals("abc"))
  • System.out.println("Equal")
  • int nNum Integer.parseInt(sMessagesnI)
  • nTotal nNum
  • catch(NullPointerException np)
  • System.out.println("Caught 1")
  • catch(NumberFormatException ne)
  • System.out.println("Caught 2")

94
Practice Quiz what will be displayed if buttons
one, two and three are pressed in that order?
  • public class TryCatchButton extends Applet
    implements ActionListener
  • Button one, two, three
  • String sMessage
  • int nTotal 0
  • public void init()
  • one new Button("one")
  • two new Button("two")
  • three new Button("three")
  • add(one)
  • add(two)
  • add(three)
  • one.addActionListener(this)
  • two.addActionListener(this)
  • three.addActionListener(this)
  • public void actionPerformed(ActionEvent ae)
  • try
  • if(ae.getActionCommand().equals("one"))
  • nTotal nTotal/nTotal

95
What is the output?
  • String sMessages "1", "two", "3"
  • for(int nI 0 nI lt 4 nI)
  • try
  • int nNum Integer.parseInt(sMessagesnI)
  • System.out.println("The number is " nNum)
  • catch(NumberFormatException ne)
  • System.out.println("Caught 1")
  • catch(ArrayIndexOutOfBoundsException ae)
  • System.out.println("Caught 2")
  • catch(NullPointerException np)
  • System.out.println("Caught 3")
  • catch(Exception e)
  • System.out.println("Caught 4")

96
Object Oriented Programming
  • In OOP we think about our program as a collection
    of interacting objects
  • In Assignment 10 (Battleship) we have a grid, and
    hidden inside that grid is a ship
  • We could design the program with two classes one
    for the grid (the applet) and one for the ship
  • We would start writing the ship class by asking
    what a ship HAS, and also what it DOES.

97
Object Oriented Programming
  • We use methods to represent what the object does
    and variables for what it has.
  • class Ship
  • //some variables
  • Ship() //constructor
  • //other methods

98
Object Oriented Programming
  • One thing a ship has is a position. If the ship
    is four cells long, we could represent the
    position as four ints (Button Numbers)
  • class Ship
  • int nShip1, nShip2, nShip3, nShip4
  • //or
  • int naShip
  • Ship() //constructor
  • //other methods

99
Object Oriented Programming
  • What a ship does is hide. It may also get hit
  • class Ship
  • int nShip1, nShip2, nShip3, nShip4
  • //or
  • int naShip
  • Ship() //constructor
  • void hide()
  • boolean isHit(int nButton)

100
Object Oriented Programming
  • Data Hiding variables are "hidden" so that they
    can only be accessed using the methods
  • private means that the variables are only
    available to the class member methods
  • public means that the methods can be used
    anywhere in the program
  • Encapsulation Hiding the details of the code
    within the class, so we as programmers can focus
    on the "big picture"

101
public and private
  • We aren't suppose to know where the ship is
    hidden, so the data should be private
  • class ship
  • private int nShip1, nShip2, nShip3, nShip4
  • //or
  • private int naShip
  • ship() //constructor
  • void hide()
  • boolean isHit(int nButton)

102
public and private
  • There is another benefit to making the data
    private
  • Any other class that uses the ship doesn't need
    to know whether the ship is represented with an
    array or not, it just needs to use the member
    methods
  • In fact, we could change from 4 separate ints to
    an array without changing any code in the applet
    class
  • This is an example of encapsulation
  • It makes code easier to use, modify and re-use

103
Using isHit()
  • public void actionPerformed(ActionEvent ae)
  • //lots of java
  • int nB Integer.parseInt(ae.getActionCommand()
    )
  • if(theShip.isHit(nB))
  • buttonArraynB.setBackground(Color.red)
  • else
  • buttonArraynB.setBackground(Color.blue)
  • //lots more java
  • repaint()

104
public and private
  • The methods should all probably be public, since
    our applet will need to use them
  • class ship
  • private int nShip1, nShip2, nShip3, nShip4
  • //or
  • private int naShip
  • public ship() //constructor
  • public void hide()
  • public boolean isHit(int nButtonNumber)

105
public and private
  • Good Style Never declare object data
    (variables) public
  • Good Style Never declare methods that other
    classes will need private

106
Practice Quiz what will be displayed the first
time paint() is called?
  • public class ClassQuiz extends Applet
  • Mystery one, two
  • public void init()
  • one new Mystery(3)
  • two new Mystery(4)
  • public void paint(Graphics g)
  • one.count()
  • two.count()
  • g.drawString("1 " one.isSome() ", "
  • one.nNum ", "
    one.dValue,20,20)
  • g.drawString("2 " two.isSome() ", "
  • two.nNum ", "
    two.dValue,20,50)
  • class Mystery
  • int nNum
  • double dValue

107
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.

108
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Draw

109
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Erase

110
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Draw

111
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Erase

112
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Draw

113
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Erase

114
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Draw

115
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Erase

116
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Draw

117
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Erase

118
Animation and threads
  • All animation is base on the same Erase Move
    Draw Wait sequence. This is sometimes called
    the Universal Animation Loop.
  • Draw

119
Animation and threads
  • In C we used delay() to wait
  • In Java, your applet is just one of many
    programs. A delay would slow them all
  • We'll avoid this problem by making our applet a
    thread
  • We can do this by implementing the runnable
    interface

120
Animation and threads
  • The runnable interface requires three methods
  • public void start()
  • public void run()
  • public void stop()
  • There is a "fill in the blank" outline for an
    applet that implements runnable in the Pong
    assignment
  • Use it a starting point for your program

121
Animation and threads
  • Let's say I want to make an animation of a
    balloon that gets bigger, that is, it "inflates"
  • I'll start by asking what a balloon has and what
    it does
  • And then I'll write a class that models the
    object
  • class Balloon
  • int nX, nY
  • int nSize
  • Balloon()
  • nX nY nSize 0
  • void inflate()
  • nSize
  • void draw(Graphics g)
  • g.fillOval(nX,nY,nSize,nSize)

122
Animation and threads
  • Once I've written my balloon class, I can "plug
    it into" the outline for a program with a thread
  • //declare other class data members
  • Balloon theBalloon
  • public void init()
  • //initialize class data members
  • theBalloon new Balloon()
  • public void paint(Graphics g)
  • theBalloon.draw(g)
  • //painting

123
Animation and threads
  • Once I've written my balloon class, I can "plug
    it into" the outline for a program with a thread
  • public void run()
  • while(true)
  • //put code that runs in loop here
  • theBalloon.inflate()
  • repaint()
  • try
  • Thread.sleep(REFRESH_RATE)
  • catch(Exception exc)

124
Normal Animation Flicker
  • g

125
Normal Animation Flicker
  • g

126
Normal Animation Flicker
  • g

127
double buffering
  • The technique of double buffering eliminates
    flickering in animation
  • It uses two "screens"
  • One is the normal screen (Graphics g)
  • One is an "invisible" screen (offscreen)
  • All drawing is done to offscreen first, and then
    copied all at once to the visible screen

128
double buffering
  • g offscreen

129
double buffering
  • g offscreen

130
double buffering
  • g offscreen

131
double buffering
  • g offscreen

132
double buffering
  • g offscreen

133
double buffering
  • g offscreen

134
double buffering
  • g offscreen
  • g.drawImage(image,0,0,this)

135
double buffering
  • To implement double buffering you need to make 6
    changes in your program
  • 1. two added declarations
  • Graphics offscreen
  • Image image
  • 2. two added initializations (in init())
  • image createImage(nSCREEN_WIDTH,
    nSCREEN_HEIGHT)
  • offscreen image.getGraphics()

136
double buffering
  • The next three changes are in paint()
  • 3. erase offscreen
  • offscreen.setColor(Color.white)
  • offscreen.fillRect(0,0,nSCREEN_WIDTH,
  • nSCREEN_HEIGHT)
  • 4. modify code so that all drawing is offscreen
  • theBall.draw(offscreen)
  • 5. copy offscreen to visible screen
  • g.drawImage(image,0,0,this)

137
double buffering
  • The last change is to override update()
  • 6. override update()
  • public void update(Graphics g)
  • paint(g)

138
The Technical Details
  • There are many technical details associated with
    flicker and many other techniques including
    "triple buffering" and "infinite buffering"
  • Here's one good website with a description
  • http//www.azillionmonkeys.com/qed/flicker.html

139
extends and inheritance
  • extends allows programmers to quickly and easily
    build a new class from an existing class
  • This is called inheritance
  • The new class inherits all the member variables
    and methods of the old class, except for
    constructors

140
extends and inheritance
  • class Person
  • String sName
  • Person()
  • sName "John"
  • void speak()
  • System.out.println
  • ("Hello, my name is " sName)

141
extends and inheritance
  • Now let's extend the Person class to make a Pro
    Wrestler
  • What do Pro Wrestlers have that normal people
    don't?

142
extends and inheritance
  • class Wrestler extends Person
  • String sGimmick
  • Wrestler()
  • sName "The incredible Hulk"
  • sGimmick
  • "Can you smell what's cooking?"
  • void speak()
  • System.out.println
  • ("Hello, my name is " sName)
  • System.out.println(sGimmick)

143
extends and inheritance
  • public class InheritanceExample extends Applet
  • Person guy
  • Wrestler hulk
  • public void init()
  • guy new Person()
  • hulk new Wrestler()
  • public void paint(Graphics g)
  • guy.speak()
  • hulk.speak()
  • / Sample Output
  • Hello, my name is John
  • Hello, my name is The incredible Hulk
  • Can you smell what's cooking?/

144
extends and inheritance
  • The Wrestler class (called the sub class)
    inherits the sName variable and the speak()
    method from the Person class (called the super
    class)
  • The Wrestler class has an additional sGimmick
    data member
  • The the speak() method is overridden ("replaced")
  • While constructors are not inherited, there is
    an "invisible call" to the default (no argument)
    constructor of the super class

145
What would happen if we didn't initialize the
wrestler's name?
  • extends and inheritance
  • class Wrestler extends Person
  • String sGimmick
  • Wrestler()
  • //sName "The incredible Hulk"
  • sGimmick "Can you smell what's cooking?"
  • void speak()
  • System.out.println
  • ("Hello, my name is " sName)
  • System.out.println(sGimmick)

146
The wrestler is also named "John"!
  • public class InheritanceExample extends Applet
  • Person guy
  • Wrestler hulk
  • public void init()
  • guy new Person()
  • hulk new Wrestler()
  • public void paint(Graphics g)
  • guy.speak()
  • hulk.speak()
  • / Sample Output
  • Hello, my name is John
  • Hello, my name is John
  • Can you smell what's cooking?/

147
extends and inheritance
  • When Java builds an instance of the Wrestler
    class (called the sub class) it starts by
    building an instance of the Person class (called
    the super class)
  • Then, whatever is extra or different is added to
    the wrestler.
  • In this case, wrestlers have an extra String
    variable for the gimmick
  • And, the speak method is different ("overridden")

148
What is the output of this code?
  • class Wolf
  • int nLegs
  • int nSize
  • Wolf()
  • nLegs 4
  • nSize 150
  • int legs()
  • return nLegs
  • int size()
  • return nSize
  • String speak()
  • class Dog extends Wolf
  • String speak()
  • return "Bark!"
  • class Collie extends Dog
  • Collie()
  • nSize 70

149
What is the output of this code?
  • Wolf BigBad new Wolf()
  • Collie Lassie new Collie()
  • System.out.println("The Big Bad Wolf is "
    BigBad.size()
  • " pounds has "
  • BigBad.legs()
  • " legs and says "
    BigBad.speak())
  • System.out.println("Lassie is "
    Lassie.size()
  • " pounds has "
  • Lassie.legs()
  • " legs and says "
  • Lassie.speak())

150
Practice Quiz Question Find the output
  • SuperClass one new SuperClass()
  • one.mystery()
  • System.out.println(one.getNum())
  • SubClass two new SubClass()
  • two.mystery()
  • System.out.println(two.getNum())

class SuperClass int nNum SuperClass()
nNum 1 System.out.println
("building a super" nNum) int
getNum() return nNum void
mystery() nNum
class SubClass extends SuperClass
SubClass() nNum 3 System.out.println
("building a sub" nNum) void mystery()
nNum 6
151
Interfacesa quick review
  • An interface is like a class, but simpler
  • An interface is just a list of methods
  • When you implement an interface, you must write
    the methods that are listed in that interface

152
interfacesa quick review
  • interface Teacher
  • public void lecture()
  • class Simon implements Teacher
  • //lots of java not shown
  • public void lecture()
  • System.out.println("blah")

153
The difference between extends and implements
  • Both inheritance (extends) and interfaces
    (implements) allow you to build new classes
    quickly, using other classes as a starting point
  • Inheritance means the new class gets all of the
    methods and data members of the parent class
    (except constructors)
  • With an interface, the classes share only those
    methods that are listedand no data

154
The difference between extends and implements
  • Inheritance means the new class is fundamentally
    the same as parent class
  • With an interface, the classes only share a few
    methods

155
The difference between extends and implements
  • An analogy
  • I (Mr. Simon) extend the Simon class I inherited
    all the data (hair, eye color, etc) and methods
    (breathe, sleep, eat, etc) of my parents
  • I implement the Teacher interface I have teach
    and grade methods
  • I also implement the Motorcyclist interface I
    have a ride method

156
The difference between extends and implements
  • Inheritance is more powerful, but you can only
    use it once a class cannot extend two different
    classes
  • With an interface, you can implement as many
    interfaces as you want however, you can not
    make an instance of an inteface
  • new Simon() //OK
  • new Motorcyclist() //NO!
  • new Teacher()//NO!

157
Pong
158
Pong
159
Pong
  • Brought the first computers into people's homes
  • Written by Alan Alcorn (a Lowell grad) for Atari
  • First Pong game was installed in a Sunnyvale bar
    in September 1972
  • Two weeks later the machine stopped
    workingbecause all the quarters had jammed it
  • Original Paddles had eight segmentsdifferent
    segments gave different angles
  • Was not the first computer game

160
Spacewar!
161
Spacewar!
  • Written by members of the MIT model railroad club
    beginning in 1961
  • They also coined the word "hack"
  • Code was kept in an unlocked draweranyone was
    free to modify it
  • Programmed on the Digital Equipment PDP-1, one of
    the first computers with a monitor
  • Club members built the world's first joysticks
  • Later modified by Atari (stolen?) to become
    Asteroids

162
Pong Spin-offs
  • Breakout 1976

163
Pong Spin-offs
  • Dr. Pong 1974

164
Pong Spin-offs
  • Pin Pong 1974

165
Pong Spin-offs
  • Pong Doubles 1973

166
Pong Spin-offs
  • Puppy Pong 1974

167
Pong Spin-offs
  • Quadra Pong 1974

168
Pong Spin-offs
  • Rebound 1974

169
Pong Spin-offs
  • Bomb Bee 1979

170
Pong Spin-offs
  • Super Pong 1974

171
Pong Spin-offs
  • 3d pong

172
Pong Spin-offs
  • circular pong

173
Pong Spin-offs
  • Warlords

174
Pong Spin-offs
  • and many, many others. . .

175
Pong
  • Think in objects Applet, Paddle, Ball
  • Start with the Ball classwhat does it have, what
    does it do?
  • class Ball
  • Ball()

176
Pong
  • class Ball
  • int nX, nY
  • Color myColor
  • Ball()

177
Pong
  • class Ball
  • int nX, nY
  • Color myColor
  • Ball()
  • nX 320
  • nY 240
  • myColor Color.red

178
Pong
  • class Ball
  • int nX, nY
  • Color myColor
  • Ball()
  • nX 320
  • nY 240
  • myColor Color.red
  • void move()
  • void bounce()
  • void draw (Graphics g)

179
Pong
  • class Ball
  • int nX, nY
  • Color myColor
  • Ball()
  • nX 320
  • nY 240
  • myColor Color.red
  • void move()
  • if( ?? )
  • nX nX 5
  • else
  • nX nX 5

180
Pong
  • class Ball
  • int nX, nY
  • Color myColor
  • boolean bRight, bUp
  • Ball()
  • nX 320
  • nY 240
  • bRight false
  • bUp true
  • myColor Color.red
  • void move()
  • if(bRight)
  • nX nX 5
  • else
  • nX nX 5

181
Pong
  • class Ball
  • int nX, nY
  • Color myColor
  • boolean bRight, bUp
  • Ball()
  • nX 320
  • nY 240
  • bRight false
  • bUp true
  • myColor Color.red
  • void move()
  • if(bRight)
  • nX nX 5
  • else
  • nX nX 5

182
Pong
  • class Ball
  • int nX, nY
  • Color myColor
  • boolean bRight, bUp
  • Ball()
  • nX 320
  • nY 240
  • bRight false
  • bUp true
  • myColor Color.red
  • void move()
  • if(bRight)
  • nX nX 5
  • else
  • nX nX 5

183
Practice Quiz Question Find the output
  • Couple bob new Couple()
  • Few jane new Few()
  • System.out.println(bob.mystery1())
  • System.out.println(jane.mystery1())
  • bob.mystery2()
  • jane.mystery2()
  • System.out.println("Bob's double is " bob.d1)
  • System.out.println("Jane's double is " jane.d1)

class Couple int n1 double d1
Couple() System.out.println("Couple")
n1 2 d1 1.5
int mystery1 () return (int)(n1d1)
void mystery2 () int nMys
mystery1() d1 nMys d1
class Few extends Couple String
sWord Few() System.out.println("Few") sWor
d "Few" int mystery1() d1
sWord.length() return (int)d1
184
How worms move
  • Starting from the back of the worm copy the x
    and y coordinates of the next segment. Stop when
    you get to the segment behind the head
  • The head coordinates change depending on the
    direction of travel

head
head
(5,2)
(6,2)
(7,2)
(5,2)
(6,2)
(5,3)
(5,3)
(5,4)
185
  • A Java programming game
  • Developed at IBM to make learning Java fun
  • Similar to TV shows like Robot Wars or Battlebots
  • Player writes Java code to build robot

186
"My First Robot"
  • package man
  • import robocode.
  • public class MyFirstRobot extends Robot
  • public void run()
  • while (true)
  • ahead(100)
  • turnGunRight(360)
  • back(100)
  • turnGunRight(360)
  • public void onScannedRobot(ScannedRobotEvent e)
  • fire(1)
  • public void onHitByBullet(HitByBulletEvent e)
  • turnLeft(90 - e.getBearing())

187
Problem Make a robot that moves in a square
  • public class Square extends Robot
  • public void run()
  • while(true)
  • ahead(50)
  • turnRight(90)
  • turnGunRight(360)
  • public void onScannedRobot(ScannedRobotEvent e)
  • fire(1)
  • public void onHitByBullet(HitByBulletEvent e)
  • turnLeft(90 - e.getBearing())

188
Problem Have robot "track" and move towards
opponent
  • public class Square extends Robot
  • public void run()
  • while(true)
  • turnRadarRight(360)
  • public void onScannedRobot(ScannedRobotEvent e)
  • turnRight(e.getBearing())
  • fire(1)
  • ahead(50)
  • public void onHitByBullet(HitByBulletEvent e)
  • turnLeft(90 - e.getBearing())

189
Problem Have robot only shoot if distance is
close
  • public class Square extends Robot
  • public void run()
  • while(true)
  • turnRadarRight(360)
  • public void onScannedRobot(ScannedRobotEvent e)
  • turnRight(e.getBearing())
  • if(e.getDistance()lt50)
  • fire(1)
  • ahead(50)
  • public void onHitByBullet(HitByBulletEvent e)
  • turnLeft(90 - e.getBearing())
Write a Comment
User Comments (0)
About PowerShow.com