Advanced Placement Computer Science Java - PowerPoint PPT Presentation

1 / 138
About This Presentation
Title:

Advanced Placement Computer Science Java

Description:

One semester of programming in C or Java with a B or better ... email account (e.g. HotMail or Yahoo mail) that you can access from the school lab ... – PowerPoint PPT presentation

Number of Views:175
Avg rating:3.0/5.0
Slides: 139
Provided by: sfu4
Category:

less

Transcript and Presenter's Notes

Title: Advanced Placement Computer Science Java


1
Advanced PlacementComputer Science(Java)
  • Mr. Simon
  • Lowell High School
  • San Francisco, CA

2
Equivalent to 2 semesters of college science
  • Course Requirements
  • One semester of programming in C or Java with a
    B or better
  • A web based email account (e.g. HotMail or Yahoo
    mail) that you can access from the school lab
  • A web site (e.g. freewebs.com) where you will
    publish your finished programs

3
Computer science vs. Computer programming
  • A computer programming course might focus on a
    programming language, it's syntax and features
  • Computer science is more abstract and includes
    studying
  • Algorithms
  • Data Structures

4
What youll learn
  • How to program in Java Applets and Applications
  • Object Oriented Programming including inheritance
  • How to write (some) HTML
  • How to maintain a website
  • Grid World Case Study
  • Searching and sorting
  • Recursion
  • Abstract classes (AB only)
  • Invariants (AB only)
  • Big O notation (AB only)
  • Linked Lists, Stacks, Queues, Trees, Heaps,
    Hashes, Maps, Sets (AB only)
  • Good Programming Style
  • A good foundation for studying computer science
    in college

5
Two exams A vs. AB
  • AB students will need to do more assignments
  • more difficult test questions
  • 2008 results 85 pass rate

A exam Grade 5 8 Grade 4 5 Grade 3 1 Grade
2 3 Grade 1 - 1
AB exam Grade 5 6 Grade 4 1 Grade 3 1 Grade
2 0 Grade 1 - 0
6
Which exam should I take?A or AB?
  • Most students should take the A exam
  • Consider taking the AB exam if
  • You have already taken Computer Programming 2
  • You are consistently scoring in the top 25 on
    class tests and quizzes
  • For most people, a 5 on the A exam looks a lot
    better than a 3 on the AB

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

8
Programming Assignments
  • Use free Windows software JCreator
  • Available online or on CD
  • 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
  • Send the code and url of your finished program to
    room334_at_gmail.com

9
Style
  • 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

10
10 point Program Grading Scale
  • 1 pt Name, class, assignment in comments at top
  • 2 pts URL/Sample Output
  • 2 pts Correct Style
  • 5 pts Program Correctness
  • Always put your name, class and assignment on the
    subject line of the email message

11
Web and email
  • Send programs to room334_at_gmail.com
  • Send questions to mrsimon_at_earthling.net
  • Check mrsimon.net for assignments, grades,
    software and other information

12
Logging On
  • User Name The last digit of graduation year
    (Class of 20055) plus first initial and last
    name, 9 characters maximum, in the user name
    field
  • Password last 4 numbers of student id
  • Log on to Choose "Lowell" from pull down menu

13
Examples
  • Example 1
  • Student nameLinda Smith
  • Class of 2004
  • ID 123456789
  • User Name4lsmith
  • Password 6789
  • Example 2
  • Student nameLinda Shakespeare
  • Class of 2007
  • ID 111110012
  • User Name 7lshakesp
  • Password 12

14
Logging On
  • If Lisa Wong and Linda Wong are in the same
    class, they would have the same user name (e.g.
    5lwong)
  • To differentiate those students, a number was
    added to the end (e.g. 5lwong2)
  • There is a list of those students online at
    http//inside.lowell.edu

15
The first time you log on
  • You will be prompted to change your password
    Choose a password that you can remember that is
    less than 8 characters in length

16
Saving your work
  • In "My Computer" you should see two network
    drives
  • Save your work to the network drive with your
    username
  • If you check Tools Folder Options Offline
    files Synchronize All offline files before
    logging off your work will still be available
    even if the school network "goes down"

17
Log Off!
  • Please remember to logoff each time you finish
    with the computer, otherwise other people will be
    able to access your home folder!

18
You can now access your work
  • on any classroom computer in any classroom
  • the library
  • the Mac lab
  • room 215
  • JROTC resource center

19
Assignment 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 free website. I
    recommend freewebs.com
  • Log Off when youre done

20
Getting your own website
  • There are several free providers of websites
  • I recommend freewebs.com, but there are many
    others and you are free to choose

21
Getting your own website
  • Other free providers of websites
  • http//pages.google.com
  • http//www.brinkster.com
  • http//geocities.yahoo.com/
  • http//www.netfirms.com
  • http//www.50megs.com
  • http//www.angelfire.lycos.com/
  • http//www.100megs.com
  • Know of any others?

22
Just Enough HTML
  • HTML can be written in a text editor like
    NotePad, WordPad or JCreator
  • HTML files must be named with an .htm or .html
    extension
  • HTML commands are called tags
  • A tag is surrounded by e.g.,
  • HTML is NOT case-sensitive so, is the same
    as

23
Just Enough HTML...
  • Some HTML tags are single and others are paired
  • The marks the end of what was begun by
    the
  • HTML is whitespace insensitive

24
Just Enough HTML...
  • - begins/end HTML
  • - begins/ends head
  • - begins/ends title
  • - begins/ends body
  • - begins/ends centered text
  • - begins/ends a headline
  • - horizontal rule
  • - end a paragraph

  • - break the line
  • - begins/ends an anchor (link)

25
Just Enough HTML...
  • Heres a proper webpage
  • This is a tiny sample
  • View this page using a browser
  • Second lineSome more text
  • And, no P at the end of the previous line see
    what happens!

26
Just Enough HTML...
  • Using Internet Explorer

27
An Introduction to Applets
  • There are two kinds of Java programs
    applications and applets
  • All the programs we wrote last semester were
    applications they have a main
  • Applets run within a browser environment (usually
    on the Internet)

28
An Introduction to Applets
  • There are two kinds of Java programs
    applications and applets
  • All the programs we wrote last semester were
    applications they have a main
  • This semester we will write Applets
  • Applets run within a web page
  • For each assignment, we will create two files
    the java program and the web page (.html)

29
Applets
  • When you visit a website and see this Java logo,
    a Java Applet is being loaded into your web
    browser
  • An applet can do almost anything that an
    application can
  • But they look differentthere is no main

30
Writing a Hello World applet in JCreator
  • The first time you start JCreator, you will see a
    screen like the one below
  • Click "Finish" to accept the file associations

31
Configuring JCreator at school to use your
network Z drive
  • Don't try this at home kids!
  • Choose Configure Options
  • Click on "Directories"
  • Under "Default Project Directory" enter Z\Java\

32
Writing a Hello World applet in JCreator
  • Open JCreator
  • Choose File Close Workspace to close any open
    files
  • Choose File New Project
  • Click on Basic Java Applet and click Next
  • Give your class a NameIll call mine Assignment1
  • Click Finish
  • JCreator automatically generates both the Java
    and html code

33
Writing a Hello World applet in JCreator
  • The Java code Assignment1.java looks like this

34
  • The html code Assignment1.htm looks like this

35
Java is very picky about names
  • Do NOT use spaces in class names.
  • It's difficult to change the name of a class.
    Make sure you choose the name you want when you
    make a new project. If you make a mistake with
    the name, it's best just to start over.
  • You can change the name of the .html file
    JCreator will give it the same name as the class
    (Assignment1.htm in this case) but you can change
    it to anything you want

36
Running the Applet
  • Choose Build Compile Project
  • You should see Process Completed
  • Choose Build Execute Project
  • You should see

37
Uploading the applet
  • When you build your applet, it creates a .class
    file
  • To put your applet on the internet, you need to
    upload
  • The .class file
  • The .html file
  • To find these files, go to your Z drive and
    look in your Java folder. Find the Assignment1
    folder, and inside of that the classes folder
  • You will then upload both Assignment1.class and
    Assignment1.htm to your website
  • You will then put a link on your homepage to
    Assignment1.htm

38
Uploading the applet
  • To upload to freewebs.com, log in, click on My
    Site and then Single File Uploader
  • Then browse to your .class and .html files one at
    a time

39
Building your homepage and linking to your
assignments
  • Click on Site Manager and then click on the Edit
    icon next to home

40
Building your homepage and linking to your
assignments
  • Move your cursor to the content box where you
    want the link to go, and click Link

41
Building your homepage and linking to your
assignments
  • Choose My Files, click on your html file, type
    some text and click Insert

42
Building your homepage and linking to your
assignments
  • You should now see the link on your homepage

43
Applets
  • We you play a game at Yahoo games, or check your
    balance in your bank account online, you are
    probably running an applet
  • An applet can do almost anything that an
    application can
  • But they look differentthere is no main

44
Applets
  • Heres about the all-time simplest applet
  • import java.awt.
  • import java.applet.
  • public class SimpleApplet extends Applet
  • public void paint(Graphics g)
  • g.drawString("Hello world", 50, 50)
  • g.drawRect(30, 30, 100, 30)

45
Applets
  • It looks like this

46
Applets
  • An applet needs a web page to run
  • The html tags that place your applet in a web
    page look like this
  • code "Assignment1.class"
  • width "500"
  • height "300"

47
Advantages of Java
  • Java is portable, the same Java program can run
    on Windows, Macintosh and Linux computers
  • This is because a Java program runs inside
    another program called the JVM (Java Virtual
    Machine)
  • You must install Java first on a computer before
    you can run a Java program

48
Applications vs. Applets
  • There are two kinds of programs you can create in
    Java
  • Applications
  • Applets
  • Applications are stand-alone programs that are
    installed on one computer
  • Applets are programs that run inside a browser
    and downloaded over the internet

49
Guidelines for Applet Creation
  • Here are some guidelines to follow to help you
    create applets
  • Well discuss the details of what they all mean
    later on
  • Every applet must have a comment at the top
    telling who wrote it, etc
  • / Mr Simon, Java Mods 10-11
  • Assignment 1 /

50
Guidelines / Applet Creation
  • Every applet must have two import statements
  • import java.awt.
  • import java.applet.
  • Every applet is stored in a file whose name is
    XYZ.java
  • Every applet has
  • public class XYZ extends Applet

51
Guidelines / Applet Creation
  • (Most) every applet contains a paint method
  • public void paint(Graphics g)
  • The body of the paint method does the drawing
    that is required

52
Guidelines / Applet Creation
  • The size of the applet is set in the HTML code in
    the applet tag
  • HEIGHT"300"
  • IMPORTANT the name of the class has to match
    both the name of the .java file and the name used
    in the applet tag.

53
Guidelines / Applet Creation
  • Good Style
  • The name of a class should always start with a
    capital letter. (e.g. MyApplet)
  • Method (function) names should start with a
    lowercase letter. If the name uses more that one
    word, capitalize each additional word. (e.g.
    drawArc)
  • Variable names should start with a lower case
    letter numPeople, dDouble, cChar, sString

54
Arithmetic in Java
  • Java uses the following arithmetic operators
    - / -- -
  • The operators can be combined with numbers to
    make expressions.
  • g.drawString(5 3,50,60)
  • //displays 8
  • Parenthesis can be used to create more
    complicated expressions
  • g.drawString(5 (2 3),50,60)

55
Literals vs. Expressions
  • If Java sees an expression it will evaluate it.
  • How could you display 5 3 to the screen, rather
    than just 8?
  • With a literal . By placing the expression in
    double quotes, Java will display it without
    evaluating it.
  • g.drawString("5 3",50,60)

56
Integer arithmetic
  • Java does division differently with integers than
    with decimals
  • g.drawString(5.0/4,50,60)
  • //displays 1.25
  • g.drawString(5/4,50,60)
  • //displays 1

57
Modulus and integer division
  • Remember how you did math in grade school?
  • g.drawString(8/5,50,60)
  • //displays 1
  • g.drawString(85,50,60)
  • //displays 3

58
Adding a number to a string
  • int nNum 5
  • g.drawString("Total " nNum, 20, 20)
  • //displays Total 5
  • The operator can be used to add a number to a
    stringmuch easier than C!
  • The order makes a difference!
  • g.drawString("X" 2 3, 20, 20)
  • //displays X23
  • g.drawString("X" (2 3), 20, 20)
  • //displays X5

59
Primitive Data Types
  • Primitive Data Types can be thought of as a
    "mailbox"
  • There are different size mailboxes (boolean,
    char, int, double, byte, short, long, float,
    etc.) for different types of data
  • Good Style Use only boolean, int, char and
    double unless you have a good reason not to.

60
Wrapper classes
  • For each primitive data type (such as int or
    double) there is a corresponding class (such as
    Integer or Double)
  • These classes (commonly known as wrapper classes)
    provide methods and constants for dealing with
    primitive data type values.
  • Primitive data types do not have methods.
    Therefore, methods related to a primitive data
    type are located in the corresponding wrapper
    class.
  • Some of the information provided by the wrapper
    classes are constants to indicate the largest and
    smallest values for a given data type. For
    example, the largest integer is 2147483647.

61
Wrapper class constants
  • Byte.MAX_VALUE // the largest value of
    type byte
  • Byte.MIN_VALUE // the smallest value of
    type byte
  • Short.MAX_VALUE // the largest value of
    type short
  • Short.MIN_VALUE // the smallest value of
    type short
  • Character.MAX_VALUE // the largest value of
    type char
  • Character.MIN_VALUE // the smallest value of
    type char
  • Integer.MAX_VALUE // the largest value of
    type int
  • Integer.MIN_VALUE // the smallest value of
    type int
  • Long.MAX_VALUE // the largest value of
    type long
  • Long.MIN_VALUE // the smallest value of
    type long
  • Float.MAX_VALUE // the largest positive
    value of type float
  • Float.MIN_VALUE // the smallest positive
    value of type float
  • Double.MAX_VALUE // the largest positive
    value of type double
  • Double.MIN_VALUE // the smallest positive
    value of type double

62
Variable Declarations
  • To create a mailbox, you declare it.
  • int nNum
  • Once its declared you can store a number
  • nNum 5
  • This is called initializing
  • You can also do both at once
  • int nValue 17

63
Variable Declarations Initializations
  • int nStudents 2535
  • double dNaturalLogBase 2.718
  • char cLetter 'a'
  • Good Style Use a prefix to show the data type,
    n for int, f for float, d for double, l for long
    and c for char
  • This is called Hungarian Notation

64
Cast
  • Most of Java's syntax comes from C, but there
    are some important differences
  • Java is stongly typed
  • This means it's very strict about data types
  • int nNum 5.6
  • In C this would store 5 in nNum, but in Java
    it's an error. To fix it you need a cast
  • int nNum (int)5.6

65
ASCII code
  • Ultimately, everything in a computer is stored as
    a (binary) number
  • The system of numbers that represent letters of
    the alphabet is called ASCII American Standard
    Code for Information Interchange
  • For example, the letter 'A' has the ASCII value
    of 65, which is stored as the binary value
    0000000001000001
  • There's a good website with all the ASCII codes
    at http//www.asciichart.com/
  • If you cast a char as an int, it will display the
    ASCII value
  • g.drawString((int)'A',50,60)
  • //displays 65

66
Graphics in Java
  • Unlike C, Java comes with built in graphics
  • Putting the following statement at the top of
    your program allows you to use the graphics
    methods
  • import java.awt.
  • There are various methods that allow us to draw
    shapes including lines, rectangles, ovals and
    polygons both unfilled and filled

67
An applet that draws a Red Square
  • import java.awt.
  • import java.applet.
  • public class RedSquare extends Applet
  • public void paint(Graphics g)
  • g.setColor(Color.red)
  • g.fillRect(20,20,100,100)

68
An applet that draws a Red Square
69
Some Graphics methods
  • void drawArc(int x, int y, int width,
  • int height,int startAngle, int arcAngle)
  • void drawLine(int x1, int y1, int x2, int y2)
  • void drawOval(int x, int y, int width,
  • int height)
  • void drawRect(int x, int y, int width,
  • int height)
  • void drawString(String s, int x, int y)
  • void fillArc(int x, int y, int width,
  • int height,int startAngle, int arcAngle)
  • void fillOval(int x, int y, int width,
  • int height)
  • void fillRect(int x, int y, int width,
  • int height)
  • Color getColor()
  • void setColor(Color color)

70
The Graphics Class
  • Drawing is done within the space specified by a
    bounding rectangle

71
The Color Class
  • There are a collection of 13 predefined colors
    Color.black, Color.blue, Color.cyan,
    Color.darkGray, Color.gray, Color.green,
    Color.lightGray, Color.magenta, Color.orange,
    Color.pink, Color.red, Color.white, Color.yellow
  • And, you can create a new color using Color(red,
    green, blue), where RGB are in the range 0-255
  • g.setColor(new Color(125,35,89))

72
The Color Class
  • Set the background color using
  • void setBackground(Color color)
  • Set the drawing color using
  • void setColor(Color color)
  • For example
  • setBackground(Color.yellow)
  • g.setColor(Color.white)
  • g.drawLine(50, 50, 100, 200)
  • g.setColor(Color.black)
  • g.drawRect(70, 80, 100, 25)

73
drawArc
  • For Assignment 2, you must use drawArc (you may
    use other methods as well)
  • drawArc has the following prototype
  • void drawArc(int x, int y, int width,
  • int height, int startAngle,
  • int arcAngle)
  • x, y, width, and height set the bounding
    rectangle

74
drawArc
  • startAngle and arcAngle set the starting point
    and length of the arc
  • g.drawArc(20, 20,200,100,90,180)

90
180
0
270
75
drawArc
  • Of course, all you see on the screen is the arc
  • g.drawArc(20, 20,200,100,90,180)

76
System.out.print() System.out.println()
  • Useful for debugging
  • like cout
  • System.out.println("Hello") is the same as
  • cout
  • System.out.print("Hello") is the same as
  • cout

77
loops
  • C and Java both have the same three types of
    loops
  • Here are three examples that all count from 1 to
    10
  • for(int nI 1 nI
  • System.out.println(nI)
  • int nJ 1
  • while(nJ
  • System.out.println(nJ)
  • nJ
  • int nK 1
  • do
  • System.out.println(nK)
  • nK
  • while(nK

78
Math.random()
  • Inside of the Math class are many variables and
    methods
  • One method random, returns a random decimal
    between 0 and 1
  • 0 n

79
Math.random()
  • Math.random()
  • 0 n

80
Math.random()
  • Math.random()2
  • (0 n

81
Math.random()
  • Math.random()2
  • (0 n
  • A random decimal from 0 to 1.9999999

82
Math.random()
  • (int)(Math.random()2)
  • ??

83
Math.random()
  • (int)(Math.random()2)
  • 0, 1

84
Math.random()
  • (int)(Math.random()10)
  • ??

85
Math.random()
  • (int)(Math.random()10)
  • 0,1,2,3,4,5,6,7,8,9

86
Math.random()
  • (int)(Math.random()10) - 5
  • ??

87
Math.random()
  • (int)(Math.random()10)- 5
  • 0,1,2,3,4,5,6,7,8,9 - 5

88
Math.random()
  • (int)(Math.random()10)- 5
  • 0,1,2,3,4,5,6,7,8,9 5
  • -5,-4,-3,-2,-1,0,1,2,3,4

89
Watch out for this mistake
  • (int)Math.random()101
  • is always zero!

90
Watch out for this mistake
  • (int)Math.random()101
  • If Math.random() is cast as an int before being
    multiplied, the result is always zero
  • The fix
  • (int)(Math.random()101)

91
Practice quiz questions Write an expression
  • The following line of code was meant to display
    the sum of 4 and 9, but it didn't work as
    expected. Fix the problem.
  • g.drawString("4 9 " 4 9,50,60)
  • Write an expression that will make a random
    decimal between 0 and 5 (including 0 but not 5)
  • Write an expression that will make a random
    integer between 0 and 5 (including 0 but not 5)
  • Write an expression that will make a random
    integer between -2 and 3 (including -2 but not 3)
  • What is the output of the following line
  • g.drawString(("One" 2) (3 4),20,20)

92
boolean
  • A primitive data type (Mailbox) that can hold
    only two values true or false
  • boolean bBool true
  • boolean bGreater 5 3
  • boolean b3Multiple (5 3) 0
  • if(b3Multiple)
  • g.drawString("Is a multiple of 3",50,50)
  • else
  • g.drawString("Is NOT a multiple of 3",50,50)

93
Objects and class
  • You wouldn't call this thing "Two wheels, a
    handlebar, a seat, some pedals and a frame"
  • Instead, you would use one name that describes
    the entire object
  • A class is a collection of primitive data types
    and methods that describe the data and behavior
    of an object
  • class Bicycle
  • int nWheels
  • double dWeight
  • double dSpeed
  • void ride()
  • dSpeed 10
  • The different parts are accessed using the dot
    operator

94
A simple class
  • A class represents an complex object
  • There are methods (functions) that represent what
    the object does
  • There are variables (mailboxes) that represent
    the object has
  • Methods that modify the variables are called
    Modifiers or Mutators
  • A special method that initializes the variables
    is called the constructor
  • Methods that retrieve the value of a variable are
    called accessors
  • Note that in Java there are two types of things
    Primitives and Objects

95
A coin flip class
  • Let's create a class that represents a coin flip
  • What it has is two sides heads and tails
  • What it is does is flip

96
A coin flip class
  • Let's create a class that represents a coin flip
  • What it has is two sides heads and tails
  • What it is does is flip
  • class CoinFlip
  • boolean bIsHeads
  • void flip()
  • //java code

97
A coin flip class
  • Let's create a class that represents a coin flip
  • What it has is two sides heads and tails
  • What it is does is flip
  • class CoinFlip
  • boolean bIsHeads
  • void flip()
  • if(Math.random()
  • bIsHeads true
  • else
  • bIsHeads false

98
Using the coin flip class
  • To use the coin flip class, we need to create a
    new coin flip object
  • CoinFlip theCoin new CoinFlip()

99
Using the coin flip class
  • To use the coin flip class, we need to create a
    new coin flip object
  • CoinFlip theCoin new CoinFlip()
  • This is called creating a new instance of
    CoinFlip or instantiating a new object
  • Now we can flip the coin and see what it is
  • theCoin.flip()
  • if(theCoin.bIsHeads)
  • g.drawString(Heads!,50,50)
  • else
  • g.drawString(Tails!,50,50)

100
The Constructor
  • CoinFlip theCoin new CoinFlip()
  • What happens if we forget to flip the coin?
  • //theCoin.flip() this line removed
  • if(theCoin.bIsHeads)
  • g.drawString(Heads!,50,50)
  • else
  • g.drawString(Tails!,50,50)
  • What value is in bIsHeads?

101
The Constructor
  • CoinFlip theCoin new CoinFlip()
  • The constructor's job is to automatically set
    up a new instance of CoinFlip
  • It has the same name as the class, and no return
    type
  • class CoinFlip
  • boolean bIsHeads
  • CoinFlip()
  • flip()
  • void flip()
  • if(Math.random()
  • bIsHeads true
  • else
  • bIsHeads false

102
The Finished Program
  • public class SimpleClassDemo extends Applet
  • public void paint (Graphics g)
  • CoinFlip theCoin new CoinFlip()
  • theCoin.flip()
  • if(theCoin.bIsHeads)
  • g.drawString("Heads!",50,60)
  • else
  • g.drawString("Tails!",50,60)
  • class CoinFlip
  • boolean bIsHeads
  • CoinFlip()
  • flip()
  • void flip()
  • if(Math.random()

103
Instantiating new Objects
  • In Java, you don't get a new Object until you ask
    for one using the Java keyword new
  • The fancy name for this is instantiating a new
    Object.
  • CoinFlip theCoin new CoinFlip()

104
Getting the value inside an object using an
accessor method
  • One way to get the value out of an object is to
    just use the dot operator
  • theCoin.bIsHeads
  • While this is the easiest way, unfortunately,
    it's not the most common
  • Usually, Java programmers use an accessor method

105
an accessor method
  • class CoinFlip
  • boolean bIsHeads
  • CoinFlip()
  • flip()
  • void flip()
  • if(Math.random()
  • bIsHeads true
  • else
  • bIsHeads false
  • boolean getFlip()
  • return bIsHeads

106
an accessor method
  • if(theCoin.bIsHeads)
  • g.drawString("Heads!",50,50)
  • else
  • g.drawString("Tails!",50,50)

107
an accessor method
  • if(theCoin.bIsHeads)
  • g.drawString("Heads!",50,50)
  • else
  • g.drawString("Tails!",50,50)

108
an accessor method
  • if(theCoin.getFlip())
  • g.drawString("Heads!",50,50)
  • else
  • g.drawString("Tails!",50,50)

109
Practice Quiz Question
  • A. Find two lines of code that instantiate new
    objects
  • B. Find two accessor methods
  • C. Find the output
  • public class SimpleClassQuiz extends Applet
  • public void paint(Graphics g)
  • Thingy Bob new Thingy()
  • g.drawString("Bob " Bob.getValue(),50,60
    )
  • WhatsIt Evelyn new WhatsIt()
  • g.drawString("Evelyn "
    Evelyn.getValue(),50,80)
  • class Thingy
  • int nNum
  • Thingy()
  • nNum 0
  • for(int nI0 nI
  • if(nI3 0)
  • nNum nI

class WhatsIt double dNum WhatsIt() dNum
1 for(int nI1 nI 0) dNum nI double
getValue() return dNum
110
The paint() and init() methods
  • The paint() method is called automatically when a
    screen update is needed
  • The paint() method may be called many times. If
    you have something that should only run once, put
    it in init()
  • init() is called once, before paint(). It's
    generally used to initialize values.

111
An applet with init() and paint() methods
  • import java.awt.
  • import java.applet.
  • public class TwoMethodDemo extends Applet
  • int nNum
  • public void init()
  • nNum 3
  • setBackground(Color.blue)
  • public void paint(Graphics g)
  • g.setColor(Color.red)
  • g.fillRect(10,10,200,200)
  • g.setColor(Color.white)
  • g.drawString("nNum is " nNum,105,105)

112
An applet with init() and paint() methods
113
Math.sqrt()
  • Inside of the Math class there is a square root
    method
  • double sqrt(double a)
  • It takes a double as an argument and returns a
    double
  • g.drawString("" Math.sqrt(100),50,50)
  • //displays 10.0

114
Boolean methods
  • Methods that return booleans are called boolean
    methods or predicates
  • Good Style Boolean methods are usually given
    names that start with is
  • isEmpty()
  • isEqual()
  • isOpen()
  • isUpperCase()

115
Practice Quiz Question
  • class Practice extends Applet
  • public void paint(Graphics g)
  • Mystery bob new Mystery()
  • g.drawString("Bob" bob.getValue(),50,50
    )
  • class Mystery
  • double dValue
  • double getValue()
  • return dValue
  • Mystery()
  • dValue 0
  • for(int nI 1 nI
  • if(isSomething(nI))
  • dValue nI

116
A "Typical" class
  • A class may have any number of methods and any
    number of variables
  • class Thingy
  • int nSomeInt
  • String sSomeString
  • Thingy()
  • int someMethod (double dNum)
  • //lots of java
  • void anotherMethod (double dNum)
  • //lots of java

117
Class member methods
  • A class may have any number of methods and any
    number of variables
  • class Thingy
  • //lots of java
  • int someMethod (double dNum)
  • //lots of java
  • The return type specifies what type of data is
    returned
  • The arguments specifies what types of data are
    passed to the method

118
Class member methods
  • A class may have any number of methods and any
    number of variables
  • class Thingy
  • //lots of java
  • int someMethod (double dNum)
  • //lots of java
  • Thingy()
  • //lots of java
  • Note that the constructor has no return type, not
    even void

119
Class member methods
  • A constructor can use arguments just like any
    other function
  • class Thingy
  • //lots of java
  • int someMethod (double dNum)
  • //lots of java
  • Thingy(int nArgument)
  • //lots of java
  • so now if we instatiate a Thingy with code like
    Thingy bob new Thingy(5) 5 is copied into
    nArgument

120
Modeling objects
  • Let's say I want to make an animation of a
    balloon that gets bigger as it is inflated
  • 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
  • ???

121
Modeling objects
  • Let's say I want to make an animation of a
    balloon that gets bigger as it is inflated
  • 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 nSize
  • Color myColor

122
The constructor's job is to initialize the member
variables
  • It puts stuff in the mailboxes when a new object
    is created
  • class Balloon
  • int nSize
  • Color myColor
  • Balloon()
  • nSize 0
  • myColor Color.red

123
What do balloon's do?
  • class Balloon
  • int nSize
  • Color myColor
  • Balloon()
  • nSize 0
  • myColor Color.red
  • ???

124
What do balloon's do?
  • class Balloon
  • int nSize
  • Color myColor
  • Balloon()
  • nSize 0
  • myColor Color.red
  • void inflate()
  • nSize

125
What do balloon's do?
  • class Balloon
  • int nSize
  • Color myColor
  • Balloon()
  • nSize 0
  • myColor Color.red
  • void inflate()
  • nSize
  • void draw(Graphics g)
  • g.setColor(myColor)
  • g.fillOval(0,0,nSize,nSize)

126
Animation and threads
  • Once I've written my ball 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

127
Animation and threads
  • Once I've written my ball 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.grow()
  • repaint()
  • try
  • Thread.sleep(REFRESH_RATE)
  • catch(Exception exc)

128
Arrays
  • An array is a collection of items of the same
    data type that is accessed by index
  • String saAnswers "yes","no","maybe"
  • g.drawString("" saAnswers1, 50,50)
  • int naNums 17,3,-5,42
  • g.drawString("" naNums2,50,70)
  • g.drawString("" saAnswers.length,50,90)
  • //note that length for arrays is NOT a function
  • g.drawString("" naNums.length,50,110)
  • /Sample Output
  • no
  • -5
  • 3
  • 4 /

129
Arrays
  • Arrays and loops are commonly used together
  • String saAnswers "yes","no","maybe"
  • for(int nI 0 nI
  • System.out.println(saAnswersnI)

130
Arrays
  • When an array is an argument of a function, the
    size of the array is not specified.
  • int someMethod(int naNums)
  • //lots of java
  • for(int nI 0 nI
  • //do something with naNumsnI
  • //return some int

131
Arrays
  • Arrays in Java work almost identically to C,
    but there are some differences in style
  • String saAnswers "yes","no","maybe"
  • //Java Style
  • String saAnswers "yes","no","maybe"
  • //C Style
  • Practice Quiz Question www.javabat.com
  • Array1Basic Array ProblemscountEvens()

132
Practice Quiz Question
  • http//javabat.com/prob?idArray2.sum13
  • Return the sum of the numbers in the array,
    returning 0 for an empty array. Except the number
    "13" is very unlucky, so it does not count and
    numbers that come immediately after a 13 also do
    not count.
  • Hint Don't worry about 13 at first, just find
    the sum of of the array
  • Then, just exclude 13
  • Finally, figure out how to exclude the number
    after 13

133
Practice Quiz Question
  • http//javabat.com/prob?idArray2.sum13
  • public int sum13(int nums)

134
Arrays of Objects
  • In Java, Arrays are objects. So if you make an
    array of objects, you need to use new twice once
    to make a new array, and then again to put new
    objects in the array.
  • Particle aBunch new Particle10
  • for(int nI 0 nI
  • aBunchnI new Particle()

135
Arrays of Objects
  • This is a great place to use a constant
  • final static int nNUM_PARTS 10
  • Particle aBunch new ParticlenNUM_PARTS
  • for(int nI 0 nI
  • aBunchnI new Particle()

136
.equals()
  • Always (well, 90 of the time) use .equals()
    instead of to compare objects
  • int nBoys 3
  • int nGirls 6
  • g.drawString("" nBoysnGirls,50,50)
  • String sWord new String(Hello)
  • String sWord2 new String(hello)
  • g.drawString("" sWord.equals(sWord2),50,70)

137
Constuctor Arguments
  • A constructor (just like any other method) can
    have any number of arguments
  • Class MumboJumbo
  • int nSum
  • MumboJumbo(int n1, int n2)
  • nSum n1 n2
  • MumboJumbo one new MumboJumbo(4,5)
  • g.drawString("" one.nSum,50,50)

138
Practice Quiz Question
  • public class ConstructArgsDemo extends Applet
  • public void paint(Graphics g)
  • int naNumbers1 7, 2, 5, 16, 1
  • int naNumbers2 3, 12, 5, 168
  • Mystery one new Mystery(naNumbers1)
  • Mystery two new Mystery(naNumbers2)
  • g.drawString("" one.bWhat, 50, 20)
  • g.drawString("" two.bWhat,50,40)
  • g.drawString("" one.sWord.equals("little"
    ),50,60)
  • g.drawString("" two.sWord.equals("little"
    ),50,80)
  • class Mystery
  • boolean bWhat
  • String sWord
  • Mystery(int naNums)
  • int nSum 0
  • for(int nI naNums.length - 1 nI 0
    nI--)
  • if(naNumsnI2 1)
Write a Comment
User Comments (0)
About PowerShow.com