Title: Computer Programming 2
1 Computer Programming 2
- Mr. Simon
- Lowell High School
- San Francisco, CA
2Course Requirements
- Successful completion of Computer Programming 1
- You should feel comfortable using the internet
and email - A web based email account (e.g. GMail or Yahoo
mail) that you can access from school - A website (free and easy to getI recommend
freewebs.com or freehostspace.com)
3Who should take this class?
- Ayone interested in a career as computer
programmer or game designer - Ayone considering a college major in
- Computer Science
- Engineering
- Math
- Physics
- Biology
- Economics
- Information Science
- Ayone curious about how software is created
4What youll learn
- OOP
- Components Event Driven Programming
- Control structures (e.g. if, while)
- Functions
- Computer Graphics
- Good Programming Style
- A good foundation for studying computer science
in college
5Grading Policy
- Each six week grade
- 70 tests and quizzes
- 20 programming assignments
- 10 productive use of lab time
- The Semester grade
- Average of the 3 six week
- grades and the final exam
6Programming Assignments
- Use free software Processing
- Available online or from me
- Its critical to your success that you spend
adequate time programming and fully understand
the assignments - Programming can be very time consumingclass time
alone may not be enough - All programs should be sent by email to
room334_at_gmail.com
7Style
- Building a working program is not enough
- Other programmers need to read, understand and
modify your program - Every class, book and job may use a slightly
different style - Good style will significantly improve your grade
810 point Program Grading Scale
- 1 pt Name, class, assignment in comments at top
- 2 pts URL (web address)
- 2 pts Correct Style
- 5 pts Program Correctness
- Always put your name, class and assignment on the
subject line of the email message
9Web and email
- Send programs to room334_at_gmail.com
- Send questions to simart_at_null.net
- Check mrsimon.net for assignments, grades,
software and other information
10Log Off!
- Please remember to logoff each time you finish
with the computer, otherwise other people will be
able to access your work!
11Assignment 0
- Send an email to room334_at_gmail.com with the
following information - Your name, reg, class and computer
- Your parents/guardians name, home phone and email
- Your parents work/daytime phone
- Secret Code (4 digits/characters, examples AOK1,
1776, KT85) - If time permits, sign up for a website at
freewebs.com or freehostspace.com - Log Off when youre done
12Getting your own website
- Providers of free websites
- http//freehostspace.com
- http//www.webs.com
- http//geocities.yahoo.com/
- http//www.netfirms.com
- http//www.50megs.com
- http//www.angelfire.lycos.com/
- http//www.100megs.com
- Know of ay others?
13freehostspace.com
- Choose the FREE Hosting Plan, and fill out the
form - Leave "Get Domain Name" field blank
- You'll be sent a username and password
14freehostspace.com
- Choose the FREE Hosting Plan, and fill out the
form - Leave "Get Domain Name" field blank
- You'll be sent a username and password
15freehostspace.com
- Once you get the confirmation email, login in,
choose Website Manager and then Subdomain Manager
16freehostspace.com
- Make up a subdomain name, and choose "Add
Subdomain" - I chose mrsimon.scienceontheweb.net
17uploading to freehostspace.com
- Choose File Manager
- Double click on the folder with your subdomain
name
18uploading to freehostspace.com
- Scroll down to the bottom of the page to find the
file upload option - You can upload 3 files at a time
19Problem Create a class to represent "flat
dice". A flat die always rolls the same number.
- First, ask "What do flat dice have? What do flat
dice do?" - They have an integer we will need one int
variable - They roll and get shown on the screen, so we'll
need at least 2 functions roll() and show()
20Problem Create a class to represent "flat
dice". A flat die always rolls the same number.
21An Instance of a class
- Creating a class is like making a blueprint for a
house - It shows what the house will look like when you
actually build it - Designing a blueprint is different from building
a house. - It's the same with a class The class shows what
dice will have and do, when some are actually
made.
22new
- When you make a new object, it is said to be an
instance of its class - In Java, you make instances of a class with the
word new - new FlatDie()
- You can create a variable for a FlatDie()
- FlatDie oneDie new FlatDie()
- int num 5
23The dot operator
- Once you have made an instance of a class, you
can access its parts with a dot - FlatDie oneDie new FlatDie()
- oneDie.roll()
- text("Roll is " oneDie.num,20,20)
24Now I'll add code to draw() so that everytime
the screen is drawn, the die shows up
- void draw()
-
- FlatDie aDie new FlatDie()
- aDie.roll()
- aDie.show(50,50)
- text("You rolled a " aDie.num,10,90)
25Now I'll add code to draw() so that everytime
the screen is drawn, the die shows up
- void draw()
-
- FlatDie aDie new FlatDie()
- aDie.roll()
- aDie.show(50,50)
- text("You rolled a " aDie.num,10,90)
26With a class writing a program with 13 flat dice
isn't much harder
27Here's what the whole program looks like
28What would be the output of this applet? (Hint
it's a trick question)
- FlatDie aDie new FlatDie()
- //aDie.roll()
- aDie.show(50,50)
- text("You rolled a " aDie.num,10,90)
29What would be the output of this applet? (Hint
it's a trick question)
- FlatDie aDie new FlatDie()
- //aDie.roll()
- aDie.show(50,50)
- text("You rolled a " aDie.num,10,90)
- Zero! Since aDie was never rolled, num was never
initialized.
30The Constructor
- A Constructor is a special function that
initializes the variables - class FlatDie
-
- int num
- FlatDie()
-
- num3
-
- //other java code not shown
31Remember Pong?
- What code should go in the Ball constructor?
- class Ball
-
- int x,y
- boolean up,right
- Ball()
-
- ???
-
- //lots more java
32Each of the 4 variables needs to be initialized
- class Ball
-
- int x,y
- boolean up,right
- Ball()
-
- x 150
- y 50
- uptrue
- rightfalse
-
- //lots more java
33Practice Quiz Question Find the output
- Thing one
- Thing two
- void setup()
-
- one new Thing()
- two new Thing()
- println("1 " one.nNum)
- two.nNum one.nNum 3
- println("2 " two.nNum)
- one.nNum two.nNum one.nNum
- println("3 " one.nNum)
-
- class Thing
-
- int nNum
- Thing()
-
- nNum 2
-
34Practice Quiz Questions
- True/False A constructor is a function.
- Fill in the blank so that num is initialized with
one of the following random integers 1,2,3,4 - int num __________________
- Find the output of the following program
- println("Testing " 1 2 3)
- println("Testing " (1 2 3))
35Problem Write a program where the dice are
different random sizes
36Problem Write a program where the dice are
different random sizes
- Now, what does every die have?
- (think, what does it have that makes it
different?) - class Die
-
- ??
37How many lines of code in the constructor?
- class Die
-
- int dots, sideLength
- Die()
-
- ??
-
38What else do we need?
- class Die
-
- int dots, sideLength
- Die()
-
- dots int(random(1,7))
- sideLength int(random(20,80))
-
- ??
39Now let's finish the program
- class Die
-
- int dots, sideLength
- Die()
-
- dots int(random(1,7))
- sideLength int(random(20,80))
-
- void show(int x, int y)
-
- fill(255)
- rect(x,y,sideLength,sideLength)
- //code for dots not shown
40- void setup() //not shown
- void draw()
-
- ??
-
- class Die
-
- int dots, sideLength
- Die()
-
- dots int(random(1,7))
- sideLength int(random(20,80))
-
- void show(int x, int y) //not shown
41- void draw()
-
- while(??)
-
- Die bob new Die()
- bob.show(??,??)
-
-
- class Die
-
- int dots, sideLength
- Die()
-
- dots int(random(1,7))
- sideLength int(random(20,80))
-
- void show(int x, int y) //not shown
42- void draw()
-
- int xPosition 0
- while(??)
-
- Die bob new Die()
- bob.show(??,??)
-
43- void draw()
-
- int xPosition 0
- while(??)
-
- Die bob new Die()
- bob.show(xPosition,150)
-
44- void draw()
-
- int xPosition 0
- while(xPosition lt 450)
-
- Die bob new Die()
- bob.show(xPosition,150)
- ??
-
45- void draw()
-
- int xPosition 0
- while(xPosition lt 450)
-
- Die bob new Die()
- bob.show(xPosition,150)
- xPosition xPosition ??
-
46- void draw()
-
- int xPosition 0
- while(xPosition lt 450)
-
- Die bob new Die()
- bob.show(xPosition,150)
- xPosition xPosition
- bob.sideLength
-
47Practice Quiz Question
- Circle the picture that best matches the output
- void setup()
-
- size(100,100)
-
- void draw()
-
- int yPos 10
- while(yPos lt 100)
-
- Widget widgie new Widget()
- widgie.show(50,yPos)
- yPos yPos widgie.diam
-
-
- class Widget
-
- int diam
- Widget()
48Writing HTML code
- Web pages are created using HTML code
- Processing automatically generates HTML code for
you, but it's useful to understand how to write
HTML yourself - HTML is not programming, it stands for HyperText
MARKUP Language - "Markup" means formatting the appearance of the
page
49Writing HTML code
- You can create HTML code with many programs, I
usually use Word Pad - HTML commands are called tags, and are between lt
gt and often come in pairs - ltHTMLgt is the tag that marks the beginning of the
of the webpage - lt/HTMLgt marks the end of the head
- Web pages are divided into a head and a body
50The head contains the title
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's Java programslt/TITLEgt
- lt/HEADgt
- lt/HTMLgt
51the title shows up at the very top
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's Java programslt/TITLEgt
52the body tag can include the background and text
colors
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's Programs!lt/TITLEgt
- lt/HEADgt
- ltBODY BGCOLORblack TEXTwhitegt
- ltCENTERgt
- lth1gtCheck out these cool programs!lt/h1gt
- lt/CENTERgt
- lt/BODYgt
- lt/HTMLgt
53BGCOLOR is background colorTEXT is the color of
the text
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's Programs!lt/TITLEgt
- lt/HEADgt
- ltBODY BGCOLORblack TEXTwhitegt
- ltCENTERgt
- lth1gtCheck out these cool programs!lt/h1gt
- lt/CENTERgt
- lt/BODYgt
- lt/HTMLgt
54Colors can also be specified with hexadecimal
codes
- ltBODY BGCOLORblack TEXT"54ff9f "gt
- ltCENTERgt
- lth1gtCheck this out!lt/h1gt
55Adding links
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's Programs!lt/TITLEgt
- lt/HEADgt
- ltBODY BGCOLORblack TEXTwhite LINKyellow
VLINKmagentagt - ltCENTERgt
- lth1gtCheck out these cool programs!lt/h1gt
- lta href"twodice.html"gtRoll Two Dicelt/agt
- lt/CENTERgt
- lt/BODYgt
- lt/HTMLgt
56LINK is the color of the links, and VLINK is the
color of the "viewed links"
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's Programs!lt/TITLEgt
- lt/HEADgt
- ltBODY BGCOLORblack TEXTwhite LINKyellow
VLINKmagentagt - ltCENTERgt
- lth1gtCheck out these cool programs!lt/h1gt
- lta href"twodice.html"gtRoll Two Dicelt/agt
- lt/CENTERgt
- lt/BODYgt
- lt/HTMLgt
57The homepage for your website is index.html
- When someone browses to your website, the first
page they see is index.html - While webs.com will automatically make an
index.html for you, freehostspace requires you to
make your own and upload it - The website has a sample homepage you can use for
your index.html - Just copy and paste it into Wordpad
58Saving from Wordpad
- Then, choose Save As
- Name it "index.html" (including the quotes)
- And choose Text Document for the type
- You are now ready to upload your homepage
59Writing a page that loads an Applet
- You can create your own custom webpages, rather
than using the ones processing creates for you - The code for the applet is pretty ugly. Rather
than write it from scratch, we'll copy it from
the html that processing makes - First, export your applet. Then right click on
index.html and open it in word pad
60Loading an Applet
- Copy the code between ltobject and lt/objectgt
right after lt!if !IE gt -- gt
61The finished page
- Here's what it looks like
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's first Java
Program!lt/TITLEgt - lt/HEADgt
- ltBODY BGCOLORblack TEXTwhitegt
- ltCENTERgt
- lth1gtCheck this out!lt/h1gt
- ltobject classid"javaTwoMoreDice.class"
- type"application/x-java-applet"
- archive"TwoMoreDice.jar"
- . . . . . . . . .Lots of HTML not shown
- lt/objectgt
- lt!--if !IEgt --gt
- lt/objectgt
- lt/CENTERgt
- lt/BODYgt
- lt/HTMLgt
62Some useful html tags
- bold ltbgttextlt/bgt
- italicized ltigttextlt/igt
- type-written ltttgttextlt/ttgt
- Headings lth1gtLargest Headinglt/h1gt through
lth6gtSmallest Headinglt/h6gt - Horizontal Rule lthrgt
- Paragraph ltpgt ... lt/pgt
- Font Sizes ltfont size1gt slightly larger font
lt/fontgt (you can use other numbers, including
negative)
63Some useful html tags
- Important Alignments add align"left" ,
align"right", align"center" i.e. lth1
align"right"gtbig heading right alignedlt/h1gt - Line break ltbrgt i.e. Line One.ltbrgtLine Two.
- Preformatted Text ltpregt ... lt/pregt
- Regular link lta href"http//url_here.com/"gttext
for linklt/agt - Mail Link lta href"mailtousername_at_host.com"gtemai
l melt/agt - Inline Images ltimg src"http//url_here.com/direc
tory/graphic.gif"gt - Center Tag ltcentergt lt/centergt
- ltimg src "somePicture.jpg"gtlt/imggt
64Some useful html tags
- (Hidden) Comments lt!-- Your user cannot see this
unless they read your source code --gt - Unordered List
- ltulgt
- ltligt first item lt/ligt
- ltligt second item lt/ligt
- lt/ulgt
- Ordered List (numbered)
- ltolgt
- ltligt item 1 lt/ligt
- ltligt item 2 lt/ligt
- lt/olgt
- ltcodegt lt/codegt Uses courier font
65GUI Components
- GUI stands for Graphical User Interface
- Things like buttons, check boxes, progress bars,
text fields, etc. - In Processing, we add libraries (extra java code)
to get GUI components - For this class, we'll use interfascia
http//www.superstable.net/interfascia/
66Install interfascia (at school)
- Borrow an interfascia CD from Mr. Simon
- Open the CD and copy the interfascia 003 folder
- Paste that folder into
- My Documents Processing libraries
- Test out your installation with the sample
program on the page after the next
67Install interfascia (at home)
- Download interfascia
- Right click on the folder, and choose "Extract
All" - Browse to My Documents Processing libraries
and click OK - Click Next and Finish
- Test out your installation with the sample
program on the next page
68An example Program
- import interfascia.
- GUIController c
- IFButton b1, b2
- int rectSize 100
- void setup()
-
- size(200, 100)
- c new GUIController (this)
- b1 new IFButton ("Bigger", 20, 40, 50, 17)
- b2 new IFButton ("Smaller", 20, 60, 50, 17)
- b1.addActionListener(this)
- b2.addActionListener(this)
- c.add (b1)
- c.add (b2)
-
- void draw()
-
- background(0)
- fill(255)
69An example Program
- import interfascia.
- GUIController c
- IFButton b1, b2
- int rectSize 100
- void setup()
-
- size(200, 100)
- c new GUIController (this)
- b1 new IFButton ("Bigger", 20, 40, 50, 17)
- b2 new IFButton ("Smaller", 20, 60, 50, 17)
- b1.addActionListener(this)
- b2.addActionListener(this)
- c.add (b1)
- c.add (b2)
-
- void draw()
-
- background(0)
- fill(255)
70import interfascia.
- import statement allows us to use other
programmer's code without cutting and pasting it
into our program - It "manages complexity" and helps to make our
program simpler and easier to read and understand
71actionPerformed()
- actionPerformed() is like mouseClicked() or
keyTyped() - When a button is pressed, actionPerformed() is
called - If there is more than one button in your program,
you can find out which button was clicked with
e.getSource()
72"Look and Feel"
- The "Look and Feel" of the button includes
- baseColor - the default color for the background
- borderColor- the color of the outline (like
stroke()) - highlightColor- the color of the button when you
hold the mouse over it - activeColor- the color of the button when you
click it - textColor- the color of the text on the button
73"Look and Feel"
- Once you create a new "Look and Feel" you apply
it to a Button after you've added the button to
the controller - You only need to do this once, usually in setup()
- Here's an example where I create a new "Look and
Feel" called newLook and apply it to Button b1 - IFLookAndFeel newLook
- new IFLookAndFeel(this,
IFLookAndFeel.DEFAULT) - newLook.baseColor color(255, 0, 0)
- newLook.highlightColor color(70, 135, 70)
- newLook.activeColor color(255,255,0)
- newLook.borderColor color(0,0,255)
- b1.setLookAndFeel(newLook)
74"Look and Feel"
- If you want all the buttons to have the same look
and feel, set the look and feel to the controller
before you add the buttons - IFLookAndFeel newLook
- new IFLookAndFeel(this,
IFLookAndFeel.DEFAULT) - newLook.baseColor color(255, 0, 0)
- newLook.highlightColor color(70, 135, 70)
- newLook.activeColor color(255,255,0)
- newLook.borderColor color(0,0,255)
- c.setLookAndFeel(newLook)
- b1 new IFButton ("Bigger", 20, 40, 50, 17)
- b2 new IFButton ("Smaller", 20, 60, 50, 17)
- b1.addActionListener(this)
- b2.addActionListener(this)
- c.add (b1)
- c.add (b2)
75Uploading to your website
- You'll notice two additional executable jar files
when you export your applet - You only need to upload core and interfascia once
76 - /
- Arithmetic operators, like -- and
- num num 2 same as num 2
- num num 17 same as num 17
- num num - 3 same as num - 3
- num num / 11 same as num / 11
- Be careful, these have side effects!
77Side effects
- is not the same as 1
- The output of the following code fragments is
different - int num 4
- println(num 1)
- println(num)
- //not the same as
- int num 4
- println(num)
- println(num)
78Side effects
- is not the same as 1
- The output of the following code fragments is
different - int num 4
- println(num 1) //displays 5
- println(num) //displays 4
- //not the same as
- int num 4
- println(num) //displays 5
- println(num) //displays 5
79Side effects
- num
- Has a side effect the value of num is now 5
- num 1
- Has no side effect the value of num is unchanged
- Rule Always use 1 unless you are sure you want
to change the value using
80What number will be displayed after buttons one,
two and three are pressed in that order?
- import interfascia.
- GUIController c
- IFButton b1, b2, b3
- int value
- void setup()
-
- size(200, 100)
- value 4
- c new GUIController (this)
- b1 new IFButton ("One", 20, 40, 50, 17)
- b2 new IFButton ("Two", 20, 60, 50, 17)
- b3 new IFButton ("Three", 20, 80, 50, 17)
- b1.addActionListener(this)
- b2.addActionListener(this)
- b3.addActionListener(this)
- c.add (b1)
- c.add (b2)
- c.add (b3)
-
81Digital Audio and Music
- You may have seen sound waves represented like
this
82Digital Audio and Music
- This is a picture representing the vibrations
that are sensed by our ears - The vibrations, called sound waves, create
pressure on our ear drum that we sense as sound
83Amplitude
- Small up and down variations like this are sensed
as soft or quiet
84Amplitude
- Large up and down swings are sensed as loud
85Frequency
- If the peaks and valleys are close together we
sense it as "high pitched" or treble
86Frequency
- If the peaks and valleys are far apart together
we sense it as "low pitched" or bass
87Demo
88Digital Audio and Music
- Sound waves are stored digitally as streams of
positive and negative decimals - Might be 0.0 0.42284906 0.76155484 0.9498813
0.9533962 0.776279 0.4595966 0.071568534
-0.30784124 -0.385844 -0.100973964 0.16315886
0.35497138 0.44508645 0.4310813 0.335351
0.19698942 0.060041666 -0.03869301
-0.079125404 -0.06222722 -0.008282244
0.05032392 0.07969847 0.055455804 -0.02892235
-0.15876007 -0.3009491 -0.41223812 -0.450995
-0.38939917 -0.22280076 0.0263986 0.311675
0.57175916 0.7444452 0.78161657 0.6618374
0.39731562 0.03329304 -0.3603183 -0.7033825
-0.9229034 -0.96936864 -0.82828283 -0.524150
89Digital Audio and Music
- Every so often, we sample the amplitude and
record it as a number - The samples in this picture are shown as vertical
lines - The third sample might be 0.0 0.42284906
0.76155484 0.9498813 0.9533962 0.776279
0.4595966 0.071568534 -0.30784124 -0.385844
-0.100973964 0.16315886 0.35497138 0.44508645
0.4310813 0.335351 0.19698942 0.060041666
-0.03869301 -0.079125404 -0.06222722
-0.008282244 0.05032392 0.07969847 0.055455804
-0.02892235 -0.15876007 -0.3009491
-0.41223812 -0.450995 -0.38939917 -0.22280076
0.0263986 0.311675 0.57175916 0.7444452
0.78161657 0.6618374 0.39731562 0.03329304
-0.3603183 -0.7033825 -0.9229034 -0.96936864
-0.82828283 -0.524150
0.76155484
90Digital Audio and Music
- The amplitude is between 1.0 and -1.0
- Just looking at this portion of the wave 0.0
0.42284906 0.76155484 0.8498813 0.9533962
0.876279 0.69362718 0.5595966 0.34587211
0.121568534 0.0 -0.25784124 -0.30627893
-0.27903551 -0.203674590 0.0
91Sound buffer
- As the sound is playing on our computer, small
chunks of numbers that record the part of the
sound we are hearing are stored in the Sound
Buffer - The size of the sound buffer is usually 512, but
can be set to other values - At 512, that means there are 512 decimals, or
floats, each between 1 and -1
92Minim
- Minim is a library that makes it easy to play
mp3s and access the Sound Buffer - Download and install Minim to the libraries
folder just like you did with interfascia - Here's a sample Minim program that plays a song
93Using Minim to play a mp3
- import ddf.minim.signals.
- import ddf.minim.
- import ddf.minim.analysis.
- import ddf.minim.effects.
- Minim minim
- AudioPlayer song
-
- void setup()
-
- minim new Minim(this)
-
- // this loads mysong.mp3 from the data folder
- song minim.loadFile("mysong.mp3")
- song.play()
-
-
- void draw() //empty for now
-
94Using Minim to get to the Sound Buffer
- To allow for stereo, there are two buffers,
song.left and song.right - We could make a very simple visualizer by using
the first value in the left buffer to change the
size of an ellipse like - void draw()
-
- background(255,0,0)
- int diameter int(
- abs(song.left.get(0)) 200 )
- ellipse(50,50,diameter,diameter)
95Using Minim to get to the Sound Buffer
- song.left.get(0) is the first float in the buffer
- Since it could be negative we'll use the absolute
value function abs() - Then we'll multiply it by 200 and drop the
decimals so we'll get a diameter between 0 and
200 for our ellipse - void draw()
-
- background(255,0,0)
- int diameter int(
- abs(song.left.get(0)) 200 )
- ellipse(50,50,diameter,diameter)
96Using the largest float in the Sound Buffer
- We can make a better visualizer by using the
largest float in the Sound Buffer - void draw()
-
- background(255,0,0)
- float biggest 0
- for(int i 0 i lt song.bufferSize() i)
-
- if(abs(song.left.get(i)) gt biggest)
-
- biggest abs(song.left.get(i))
-
-
- int diameter int(200 biggest)
- ellipse(50,50,diameter,diameter)
97Using the all the floats in the Sound Buffer
- We could write a loop to use all the floats in
the Buffer - void draw()
-
- background(255,0,0)
- for(int i 0 i lt song.bufferSize() i)
-
- float amplitude song.left.get(i)
- int height int(200 amplitude)
- rect(i,50,2, height)
-
98Practice Quiz Question
- Circle and modify the parts of the code on the
following page, so that the dice are smaller, and
there are gaps of 50 on each side of the dice
(i.e. the x position of the first die is 50 and
the last is 550)
Before
After
99- void setup()
-
- size(600,200)
- //other code not shown
-
- void draw()
-
- background(0)
- int xPosition 0
- while(xPosition lt 600)
-
- Die one new Die()
- one.show(xPosition,100)
- xPosition xPosition one.sideLength
-
-
- class Die
-
- int roll, sideLength
100Loops
- Loops make things happen over and over again
- If you are doing the same thing over and over
again with small variations, use a loop - For example, you could write a loop to display
six Xs - X X X X X X
101Loops
- for(int i ? i lt ? i?)
-
- print("X ")
-
- X X X X X X
102Loops
- for(int i 1 i lt 6 i)
-
- print("X ")
-
- X X X X X X
103Nested Loops
- Now, how would I repeat that pattern three times
so that it looked like this? - X X X X X X
- X X X X X X
- X X X X X X
104Nested Loops
- for(??)
-
- for(int i 1 i lt 6 i)
-
- print("X ")
-
- ??
-
- X X X X X X
- X X X X X X
- X X X X X X
105Nested Loops
- for(int j 1 j lt 3 j)
-
- for(int i 1 i lt 6 i)
-
- print("X ")
-
- println() //ends the line
-
- X X X X X X
- X X X X X X
- X X X X X X
106Nested Loops
- Putting a loop inside another loop is called
Nesting - for(int j 1 j lt 3 j)
-
- for(int i 1 i lt 6 i)
-
- print("X ")
-
- println() //ends the line
107Nested Loops
- Notice the row and column arrangement
- for(int j 1 j lt 3 j)
-
- for(int i 1 i lt 6 i)
-
- print("X ")
-
- println() //ends the line
-
- X X X X X X
- X X X X X X
- X X X X X X
3 rows
108Nested Loops
- Notice the row and column arrangement
- for(int j 1 j lt 3 j)
-
- for(int i 1 i lt 6 i)
-
- print("X ")
-
- println() //ends the line
-
- X X X X X X
- X X X X X X
- X X X X X X
6 columns
109Nested Loops
- Which loop is generating the three rows?
- Which loop is generating the six columns?
- for(int j 1 j lt 3 j)
-
- for(int i 1 i lt 6 i)
-
- print("X ")
-
- println() //ends the line
-
- X X X X X X
- X X X X X X
- X X X X X X
110A good thing to remember
- The outer loop can be used to generate a number
of rows - The inner loop can be used to generate a number
of columns - for(int j 1 j lt 3 j)
-
- for(int i 1 i lt 6 i)
-
- print("X ")
-
- println() //ends the line
-
111Practice Quiz Question
- Write a program using nested loops that will
create the following pattern of Xs - X X X X X
- X X X X X
- X X X X X
- X X X X X
112Nested loops and graphics
- Let's say I wanted to make a grid of circles that
looked like this - I can tell it has 8 rows and 6 columns
- So I'll need appropriate loops
113One loop will make the x coordinates and the
other the y
- for( ?? ) //8 rows
-
- for( ?? ) //6 columns
-
- ellipse(x,y,5,5)
-
114If I move down one row, what's changing, x or y?
- for( ?? ) //8 rows
-
- for( ?? ) //6 columns
-
- ellipse(x,y,5,5)
-
115The outer loop changes y and the inner loop
changes x
- for(int y ?? y lt ?? y ?? ) //8 rows
-
- for(int x ?? x lt ?? x ?? //6 columns
-
- ellipse(x,y,5,5)
-
116The outer loop changes y and the inner loop
changes x
- for(int y 10 y lt 80 y 10 ) //8 rows
-
- for(int x 20 x lt 70 x 10 //6 columns
-
- ellipse(x,y,5,5)
-
117The outer loop changes y and the inner loop
changes x
- for(int y 10 y lt 80 y 10 )
- //8 rows at 10 20 30 40 50 60 70 80
-
- for(int x 20 x lt 70 x 10
- //6 columns at 20 30 40 50 60 70
-
- ellipse(x,y,5,5)
-
118Practice Quiz Question
- Write a program using nested loops that will
create a similar pattern of ellipses
119Practice Quiz Question
- If it's helpful, here are some coordinates
- (Yours doesn't have to look exactly like mine)
1202 dimensional arrays
- Can be thought of as a grid with rows and
columns
column 0 1 2
-3
-1
5
row 0
7
12
13
row 1
1212 dimensional arrays
- int nums -3, -1, 5,
- 7, 12, 13
- //Note rows first, then columns
- println(nums12) //displays 13
- println(nums21) //Crash!
column 0 1 2
-3
-1
5
row 0
7
12
13
row 1
122The Battleship program
- In Battleship, we have a two dimensional array of
buttons - IFButton buttons
-
123The Battleship program
- Don't worry too much about the arithmetic in the
nested loops that is arranging them into rows and
columns - for(int r 0 r lt rows r)
-
- for(int c 0 c lt cols c)
-
- int x c buttonSize 40
- int y r buttonSize 60
- buttonsrc new IFButton ("", x, y,
buttonSize, buttonSize) - buttonsrc.addActionListener(this)
- control.add (buttonsrc)
-
-
-
124The Battleship program
- In OOP we think about our program as a collection
of interacting objects - In the Battleship program, the objects include
Buttons and a Ship - The Button class has already been written, but we
will need to write a class that models a Ship - Before writing code for the Ship class, we should
ask ourselves what a ship HAS, and also what it
DOES. -
125The Battleship program
- We use functions to represent what the object
does and variables for what it has. - class Ship
-
- //some variables
- Ship() //constructor
-
-
- //other functions
-
126The Battleship program
- Our Ship is hiding behind four Buttons, so our
class will need four IFButton variables - class Ship
-
- IFButton b1,b2,b3,b4
- Ship() //constructor
-
-
- //other functions
-
127The Battleship program
- The constructor's job is to initialize the
variables - class Ship
-
- IFButton b1,b2,b3,b4
- Ship() //constructor
-
- b1 ??
- b2 ??
- b3 ??
- b4 ??
-
- //other functions
-
128The Battleship program
- Eventually we'll hide the ship randomly, but to
get started, we can just choose any four buttons - class Ship
-
- IFButton b1,b2,b3,b4
- Ship() //constructor
-
- b1 buttons02
- b2 buttons12
- b3 buttons22
- b4 buttons32
-
- //other functions
-
129Creating an instance of the ship class
- Once we have the beginnings of a ship class, we
can make an instance with code like - Ship bob new Ship()
130Checking for a hit
- void actionPerformed (GUIEvent e)
-
- IFButton shot (IFButton)e.getSource()
- if(shot.getX() gt 145) //replace this with
- //code that checks for a hit
-
- shot.setLookAndFeel(hit)
-
- else
-
- shot.setLookAndFeel(miss)
-
131How can we find out if bob was hit?
- void actionPerformed (GUIEvent e)
-
- IFButton shot
- (IFButton)e.getSource()
- if( bob ?? )
-
- shot.setLookAndFeel(hit)
-
- else
-
- shot.setLookAndFeel(miss)
-
132The isHit function
- We'll check to see if shot is the same button as
b1, b2, b3, or b4 - class Ship
-
- IFButton b1,b2,b3,b4
- Ship() //constructor
-
- b1 buttons02
- b2 buttons12
- b3 buttons22
- b4 buttons32
-
- boolean isHit(IFButton shot)
-
- return false //replace this with code that
checks to - //see if the ship was hit
-
-
133Now we can call isHit()
- void actionPerformed (GUIEvent e)
-
- IFButton shot
- (IFButton)e.getSource()
- if( bob.isHit(shot) true )
-
- shot.setLookAndFeel(hit)
-
- else
-
- shot.setLookAndFeel(miss)
-
134A trick question!
- How many Buttons does the following code create?
- IFButton b1
135None!
- Buttons are Objects
- What word do we need in Java to build an instance
of a class? - IFButton b1
136new
- Now one Button, called an instance has been
created - IFButton b1
- b1 new IFButton ("one",20,40,50,17)
137So, if this isn't a Button, what is it?
138It's just a name for a Button
- IFButton b1
- It's kind of like saying "If I ever get a dog,
I'll name him Bob" - We have a name for Button that hasn't been
created yet - In programming we this kind of name a pointer
139The Binky video
- Pointer Fun is a 3 minute video from the computer
science dept. at Stanford
140- //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
141x
y
142x
y
14342
x
y
14442
x
y
145- y.value 13
- //Null Pointer exception
42
x
y
CRASH!
14642
x
y
14713
x
y
148- //What would
- println(x.value)
- //Display?
13
x
y
14913
x
y
150- Change the code from the Binky video
- so that it produces this structure
1
x
2
y
class IntObj int value IntObj x
IntObj y x new IntObj()
x.value 42 y x
y.value 13 println(x.value) println(y.value
)
151Practice Quiz Question Find the Output if
Buttons b1 and b2 are clicked in that order
- import interfascia.
- GUIController c
- IFButton b1, b2
- int nTimes 0
- SomeClass bob
- void setup() //not shown
- void draw()//not used
- void actionPerformed(GUIEvent e)
-
- nTimes
- println(
- "clicked " nTimes " times")
- IFButton clicked
- (IFButton)e.getSource()
- if(bob.mystery(clicked)false)
-
- println("first")
-
- else
class SomeClass IFButton theButton
SomeClass() theButton b2 boolean
mystery( IFButton clicked)
if(theButtonclicked) return true
else return false
152dot equals vs. double equals
- 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?
153X Y refer to the same object
2
x
y
154X Y have the same value
2
x
2
y
155Practice Quiz Question What is the output of
this applet?
- SomeType one new SomeType("one")
- SomeType two new SomeType("two")
- void setup()
-
- SomeType three two
- three.sMessage new String("three")
- println(one.sMessage ", " two.sMessage)
- three one
- three.sMessage new String("four")
- println(one.sMessage ", " two.sMessage)
-
- void draw()//not used
- class SomeType
-
- String sMessage
- SomeType(String sText)
-
- sMessage sText
-
156- SomeType one new SomeType("one")
- SomeType two new SomeType("two")
one
one
two
two
157- SomeType three two
- three.sMessage new String("three)
- System.out.println(one.sMessage
- ", " two.sMessage)
one
one
three
two
three
158- three one
- three.sMessage new String("four)
- System.out.println(one.sMessage
- ", " two.sMessage)
four
one
three
two
three
159primitives (likes ints) are different than
objects
- int n1 3
- int n2 n1
- n2 7
- println(n1)
160There are two int "mailboxes" and each has a 3
- int n1 3
- int n2 n1
- n2 7
- println(n1)
n1
3
n2
3
161There are two int "mailboxes" and each has a 3
- int n1 3
- int n2 n1
- n2 7
- println(n1)
- //displays 3
n1
3
n2
7
3
162objects are created with class
- class IntObj
-
- int value
-
- IntObj n1 new IntObj()
- n1.value 3
- IntObj n2 n1
- n2.value 7
- println(n1.value)
163We've only created one new IntObj
- class IntObj
-
- int value
-
- IntObj n1 new IntObj()
- n1.value 3
- IntObj n2 n1
- n2.value 7
- println(n1.value)
n1
3
n2
164We've only created one new IntObj
- class IntObj
-
- int value
-
- IntObj n1 new IntObj()
- n1.value 3
- IntObj n2 n1
- n2.value 7
- println(n1.value)
- //displays 7
n1
7
n2
165find the output
- int n1 4
- int n2 n1
- n2 2
- println(n1)
- class IntObj
-
- int value
-
- IntObj n3 new IntObj()
- n3.value 4
- IntObj n4 n3
- n4.value 2
- println(n3.value)
166null pointer exception
- Remember what happened to Binky?
- Don't let it happen to you!
- Make sure your pointers are all assigned to point
to something - If you try to use a pointer that isn't pointing
to something, your program crashes
167a nasty null pointer exception
- Ship bob
- void setup()
-
- Ship bob new Ship()
- //lots more java
-
- void actionPerformed()
-
- IFButton shot(IFButton)e.getSource()
- if(bob.isHit(shot) true)
- //lots more java
-
168How many bob pointers?
- Ship bob
- void setup()
-
- Ship bob new Ship()
- //lots more java
-
- void actionPerformed()
-
- IFButton shot(IFButton)e.getSource()
- if(bob.isHit(shot) true)
- //lots more java
-
169Now it's fixed
- Ship bob
- void setup()
-
- bob new Ship()
- //lots more java
-
- void actionPerformed()
-
- IFButton shot(IFButton)e.getSource()
- if(bob.isHit(shot) true)
- //lots more java
-
170Arrays of Objects
- A very powerful technique
- Let's say you have a planet class and want to
model the solar system - First, you'd declare an Array of Planets
- Planet planets
171Arrays of Objects
- Then you would initialize the array
- Planet planets
- void setup()
-
- //other code not shown
- planets new Planet8
172Arrays of Objects
- How many new Planets have been created?
- Planet planets
- void setup()
-
- //other code not shown
- planets new Planet8
173Arrays of Objects
- None! All we have are 8 pointers.
- Planet planets
- void setup()
-
- //other code not shown
- planets new Planet8
174Arrays of Objects
- We nee to loop through the array to "hook those
pointers up" to new Planets - Planet planets
- void setup()
-
- //other code not shown
- planets new Planet8
- for(int i0 ilt8 i)
-
- planetsi new Planet()
175Arrays of Objects
- Once the array is set up, you can loop through it
to draw and move the planets - void draw()
-
- for(int i0 ilt8 i)
-
- planetsi.move()
- planetsi.show()
176An outline for the Snake game
- Snake theSnake
- //other variables not shown
- void setup()
-
- size(600,410)
- theSnake new Snake( ??? )
- //lots more java
-
- void draw()//not shown
- void keyPressed()
-
- theSnake.direction keyCode
-
- class Segment
-
- //variables and functions not shown
-
- class Snake
177The Segment class
- Represents one of the squares that form the body
of the snake - Should have everything that Segments have and do
- class Segment
-
- ??
-
178The Segment class
- What Segments have x and y coordinates, a length
for the side of the segment, and a color. - What Segments do get constructed and shown to
the screen - class Segment
-
- ??
-
179The Segment class
- What Segments have x and y coordinates, a length
for the side of the segment, and a color. - class Segment
-
- int x, y, length
- color snakeColor
-
180The Segment class
- What Segments do get constructed and shown to
the screen - class Segment
-
- int x, y, length
- color snakeColor
- Segment()
-
- x ???
- y ???
- length ???
- snakeColor ???
-
- void show() ???
-
181The Snake class
- Represents the entire Snake
- Should have everything that Snakes have and do
- class Snake
-
- ??
-
182The Snake class
- Snakes have An array of segments, a direction,
the current length of the snake, and the maximum
length of the snake - class Snake
-
- ??
-
183The Snake class
- Snakes have An array of segments, a direction,
a color, the current length of the snake, and the
maximum length of the snake - class Snake
-
- Segment segments
- int direction
- int currentLength
- int maxLength
-
184The Snake class
- What Snakes do They get constructred, moved and
drawn to the screen - class Snake
-
- Segment segments
- int direction
- int currentLength
- int maxLength
- Snake() ???
- void move() ???
- void show () ???
-
185The Snake constructor
- class Snake
-
- Segment segments
- int direction
- int currentLength
- int maxLength
- Snake()
-
- direction ???
- direction ???
- currentLength ???
- maxLength ???
-
-
186Initializing the array of segments is probably
the trickiest part of the constructor
- Snake()
-
- //other code not shown
- segments new SegmentmaxLength
- for(int i 0 i lt maxLength i)
-
- segmentsi new Segment())
-
- //change the color of the head
- segments0.snakeColor
- color(255,255,0)
-
187How snakes move
- Starting from the back of the snake 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)
188Find the output
- char letters1 'b','c','d','e'
- char letters2 'b','c','d','e'
- letters10 'a'
- for(int i 1 i lt letters1.lengthi)
-
- letters1i letters1i - 1
-
- println(letters1)
- for(int i letters2.length-1 i gt 0i--)
-
- letters2i letters2i - 1
-
- letters20 'a'
- println(letters2)
189Recursionused inFractals
190What will be displayed?
- void setup()
-
- randomNumber()
-
- void draw()//not used
- void randomNumber()
-
- println(random(1))
191What will be displayed now?
- void setup()
-
- randomNumber()
-
- void draw()//not used
- void randomNumber()
-
- println(random(1))
- randomNumber()
192The program shows a bunch of random numbers and
then crashesthe problem is it won't stop!
- void setup()
-
- randomNumber()
-
- void draw()//not used
- void randomNumber()
-
- println(random(1))
- randomNumber()
193Recursion A function that calls itself
- void randomNumber()
-
- println(random(1))
- randomNumber()
-
- Recursion is another way of making a loop
- Recursion is hard to controlit's very easy to
create an infinite loop that never stops
194In recursion, the "stopping point" is called the
base case
- void randomNumber(int times)
-
- if(times 0)
-
- println("Stop!")
-
- else
-
- println(random(1))
- randomNumber(times-1)
-
- The base case stops the recursive calls
195- void setup()
-
- randomNumber(5)
-
- void randomNumber(int times)
-
- if(times 0)
-
- println("Stop!")
-
- else
-
- println(random(1))
- randomNumber(times-1)
-
-
196Recursion
- There are two basic ways to make things happen
"over and over again" in programming - Loops
- Recursion
- In theory, anything you can do with loops, you
can do with recursion ( vice versa)
197A loop that "counts" from 1 to 10
- void setup()
-
- for(int i 1 i lt 10 i)
-
- println(i)
-
198A Recursive Function that "counts" from 1 to 10
- void setup()
-
- recursiveFunction(1)
-
- void recursiveFunction(int num)
-
- if(num 10)
-
- println(num " and stop")
-
- else
-
- println(num)
- recursiveFunction(num1)
-
199A Recursive Function calls itself
- void recursiveFunction(int num)
-
- if(num 10)
-
- println(num " and stop")
-
- else
-
- println(num)
- recursiveFunction(num1)
-
-
200Just like a loop, it has a starting point, a
stopping point, and a way to get from one to the
other
- void setup()
-
- recursiveFunction(1)
-
- void recursiveFunction(int num)
-
- if(num 10)
-
- println(num " and stop")
-
- else
-
- println(num)
- recursiveFunction(num1)
-
201base case
- Just like a loop, if recursion doesn't stop,
we'll crash the computer - void recursiveFunction(int num)
-
- if(num 10)
-
- println(num " and stop")
-
- else
-
- println(num)
- recursiveFunction(num1)
-
-
- The if statement is called the base case
- In the base case there is no recursive call, and
the recursion stops
202What is the output?
- void setup()
-
- println(mystery(4))
-
- int mystery(int num)
-
- if(num lt 1)
-
- return 1