Title: Lecture 4: Expressions
1Lecture 4 Expressions Conditionals
- Some review
- Number Expressions
- String Expressions
- Conditionals
2The story so far
- Every program is constructed by completing a
class definition - Class definition consists of
- Class header
- Variable declarations
- Method definitions
- Vars and methods inside curly braces,
public class ClassName
private FilledRect myRect
public void onMouseClick(Location point)
3The story so far
- Method definitions consist of
- Method header
- A list of statements
- All grouped together by curly braces
public void onMouseClick(Location point)
new FilledOval(50, 50, 40, 30, canvas) myRect
new FilledRect(20, 20, 10, 10, canvas) myRect.set
Color(Color.green)
4The story so far
- A methods name determines when the statements in
it are performed - In particular, we know these methods so far
public void begin() public void
onMousePress(Location point) public void
onMouseRelease(Location point) public void
onMouseClick(Location point) public void
onMouseEnter(Location point) public void
onMouseExit(Location point) public void
onMouseMove(Location point) public void
onMouseDrag(Location point)
5The story so far
- And, we know that there are (at least) 3 kinds of
statements - Constructions
- Method invocations
- Assignments
new FilledRect(40, 40, 30, 50, canvas) new
Text(Hello!, 30, 50, canvas)
canvas.clear() myRect.seColor(Color.green)
myRect new FilledRect(20, 10, 30, 30,
canvas) myLocation point
6The story so far
- Finally, we know how to make 2 kinds of comments
- Line comments
- Multi-line comments
// this comment is one line long.
/ This comment spans multiple
lines /
7The story so far
- On Variable declarations
- Declarations make a box that can hold an object
of a particular type - This box starts out empty, and you need to fill
it with an assignment
myText
Declaration
Text myText
8The story so far
- On Variable declarations
- Declarations make a box that can hold an object
of a particular type - This box starts out empty, and you need to fill
it with an assignment
myText
Hello!
Declaration
Text object, created by constructor
Text myText new Text(Hello!, 40, 40, canvas)
9The story so far
- On Variable declarations
- Declarations make a box that can hold an object
of a particular type - This box starts out empty, and you need to fill
it with an assignment
myText
Hello!
Assignment associates declared name with created
object!
Declaration
Text object, created by constructor
Text myText myText new Text(Hello!, 40, 40,
canvas)
10A bit on Locations
- We looked at Location objects, and found that
theyre just coordinate pairs - Can use a Location where youd expect an x,y pair
- What if you just want x or y?
- Why would we want to do that?
- Check out CrossHairs program example
- We need some way to get x or y coord by itself
new FramedRect(point, 40, 50, canvas)
11CrossHairs
import objectdraw. import java.awt. / A
program that draws perpendicular lines that move
so that they always intersect at the mouse's
current position / public class CrossHairs
extends WindowController private Line vert,
horiz // Initially center the lines public
void begin() vert new Line( 200, 0, 200,
400, canvas ) horiz new Line( 0, 200, 400,
200, canvas ) // move the lines so that
they intersect at the mouse public void
onMouseDrag(Location point) vert.setEndPoints(
point.getX(), 0 , point.getX(),
400 ) horiz.setEndPoints( 0, point.getY()
, 400, point.getY() )
12Accessor Methods
- In Java you do this using something called an
accessor method - For locations, the relevant accessors are
- getX()
- getY()
- So, to get the x coord of a point, youd write
- Likewise, for y
point.getX()
point.getY()
13Accessor Methods
- Remember setColor()?
- This was a mutator method
- Mutator methods change something about an object
- setColor changes color (duh)
- Remember void?
- Mutators are typically declared to be void
- This means they just perform some task
- Accessors are different!
14Accessor Methods
- Invocation of an accessor method is the same as
that of a mutator - Usage is very different
- Accessor produces some piece of needed info
- Can use wherever pieces of information are
required - What are some examples of places like this?
point.setColor(Color.green)
//mutator point.getX()
//accessor
15Accessor Methods
- Examples of places to use accessors
- As an actual parameter
- On the right hand side of an assignment statement
new FilledRect(point.getX(), point.getY(), 50,
50, canvas) new FilledRect(point.getY(),
point.getX(), 50, 50, canvas)
someNumber point.getX()
16Accessor Methods
- Example onMouseDrag() in CrossHairs
- This makes the two crossing lines based on the
mouses position - vert and horiz are just Line objects, declared as
variables in the program
public void onMouseDrag(Location point)
vert.setEndPoints( point.getX(), 0 ,
point.getX(), 400
) horiz.setEndPoints( 0, point.getY() ,
400, point.getY() )
17Numeric variables
- So far, all our variables have been objects,
e.g. - FilledRects
- Lines
- Locations
- We know how to do a few things with them
- Construct new Objects
- Associate names with objects
- Invoke methods on objects
18Numeric variables
- Weve seen numbers too, as parameters to
constructors - And as x and y parts of Locations
- getX() and getY() are said to return numbers
- Can be used the same way
- Think of the methods as leaving a number behind
after they run
new FilledRect(30, 30, 50, 50, canvas)
new FilledRect(point.getX(), point.getY(), 50,
50, canvas)
19Numeric variables
- Numbers are different, in that you cant
- construct them
- call methods on them
- But, you can
- Declare instance variables for numbers
- Perform math operations on them (like or -)
new Number(7) // error!
7.moveTo(8) // error!
20Declaring Numbers
- In Java, all declarations must have a type
- Whats the type for numbers?
- Two numeric types (that you should care about)
- int is the Java type for integers
- double is the Java type for real numbers
- Somebody tell me what the difference is between
integers and real numbers!
21Declaring Numbers
- You can declare numeric instance vars like this
- Same as for objects
- Type followed by a name
- Type is just int or double now
- Note that these are lowercase, whereas object
types tend to be capitalized!
int count //integer variable to store a
count double percent //real number to store a
percentage
22Operators
- Java provides the usual arithmetic operators
- addition
- - subtraction
- multiplication
- / division
- Division is different for ints and doubles
- For doubles, its what youd expect
- Division of ints returns integer part of the
quotient - There is another operator, (pronounced mod,
for modulo) to get the remainder.
23Using Operators
int x int y x 5 7 4 //x is 39 y x
2 //y is 41
double a double b a 5.47 b 3.5 b a /
b //b is 1.56285714285714
24ClickCounter
- Heres a program that counts clicks in an int
public class ClickCounter extends
WindowController // the number of
clicks private int count // initialize
the counter to 0 public void begin() count
0 // increment the counter public void
onMouseClick(Location point) count count
1
25Text and Strings
- We saw that when we create a new Text, we have to
provide the words to write in quotes - The quoted text is called a String literal
- A String is a type of object for holding text
- literal is a term used in programming languages
for when you write out the value of something - e.g. an integer literal is just a number, like 5
or 79 - Well learn lots about Strings later on, but for
now lets talk about how to combine them to
create useful messages
new Text(Hello World!, 40, 30, canvas)
26Text and Strings
- It turns out that you can pass an int to the Text
constructor - This will create a Text object that says 5
- What if you wanted to write out a message for
number of clicks, e.g. - You have clicked 12 times
new Text(5, 40, 30, canvas)
27Text and Strings
- Could make 3 text objects
- Have to carefully position these
- seems like a huge pain to set up the coordinates
ourselves - I probably got it wrong above!
new Text(You have clicked 0, 40, canvas) new
Text(count, 60, 40, canvas) new Text( times.,
70, 40 canvas)
28Concatenation
- Better solution is to concatenate Strings
- Big word for put together
- Use the operator with Strings to concatenate
- Or just
String message message You have clicked
count times. new Text(message, 0, 40,
canvas)
new Text( You have clicked count
times., 0, 40, canvas )
29Concatenation
- Note that Java doesnt add or remove spaces!
- This
- Gives us
- Suppose you have a Location, called point, and
you want to display its coordinates as text in
parentheses - Like this (24, 35)
This is a String.
This isa String.
"(" point.getX() "," point.getY() ")"
30Displaying the Mouse Location
// program to display current location of the
mouse public class MouseMeter extends
WindowController // the text message to
be displayed private Text display
public void begin() display
new Text("Move the mouse", 0, 0, canvas)
// display coordinates of mouse
whenever it is moved public void
onMouseMove(Location point)
display.setText( "(" point.getX() ","
point.getY() ")" )
31Constants
- You probably noticed that the programs weve
written had a lot of numbers in them - You can associate some of these numbers with
names so that youre reminded of what the numbers
mean - Two ways to do this in Java
new Text(Hello, 40, 50, canvas)
32Constants
- You probably noticed that the programs weve
written had a lot of numbers in them - You can associate some of these numbers with
names so that youre reminded of what the numbers
mean - Constant names are usually ALL_CAPS
- We might rather say
new Text(Hello, 40, 50, canvas)
new Text(Hello, SCREEN_WIDTH, SCREEN_HEIGHT,
canvas)
33Constants
- 2 things to know when declaring constants
- You can assign an initial value to a variable in
its declaration - If you include static final in the declaration,
the value will never be allowed to change - By convention, you should capitalize static final
variable names
int myNumber 0 double myDouble 0.567
private static final int CONSTANT_NUMBER
5 private static final int SCREEN_WIDTH 500
34Constants
- You can make object constants, too
- But, constants cant depend on objects created
when the program starts up! - canvas is one of these
- However, constants can depend on other constants
private static final String FILE_NAME
settings.txt private static final Location top
new Location(250, 6)
private static final FilledRect rect new
FilledRect(40, 40, 50, 40, canvas) // error!
private static final int TOP_X 250 private
static final int TOP_X 6 private static final
Location top new Location(TOP_X, TOP_Y)
35Conditionals
- Lets make the click counter into a really
exciting Basketball game! - See the Basketball example for what I have in
mind - Ok, so it sucks. Well call it Duke Basketball
- To play Duke Basketball, we need to
- Draw a hoop on the screen (a FramedOval )
- Add 2 instead of 1 every time you click
- Only add if you click within the hoop.
36Conditionals
- Look at that last condition
- Only add if you click within the hoop.
- We dont know how to say that yet
- We have to learn how to tell Java to check that
some condition is true before performing an
action. - In English, you might say
- if the point where you click is in the hoop,
then add 2 to the score
37Conditionals
- In Java, you say almost the same thing
- Two new features here
- The contains() method
- This tells you if a Location falls inside some
object - The if statement
if (hoop.contains(point)) score score
2
38Code for Basketball
import objectdraw. import java.awt. //
program that displays how many times the mouse
has been clicked public class Basketball extends
WindowController // Location of the display
private static final int DISPLAY_X 150
private static final int DISPLAY_Y 200
private static final int DISPLAYSIZE 16 // in
points // Location and dimensions of the
hoop private static final int HOOPTOP 50
private static final int HOOPLEFT 160
private static final int HOOPWIDTH 100
private static final int HOOPHEIGHT 60 //
the Text object which displays the count
private Text display // the oval that
represent the hoop private FramedOval hoop
// the number of points private int score
// initialize the counter and the text message
public void begin() score 0
display new Text("Your score is 0",
DISPLAY_X, DISPLAY_Y, canvas)
display.setFontSize(DISPLAYSIZE) hoop
new FramedOval( HOOPLEFT, HOOPTOP,
HOOPWIDTH, HOOPHEIGHT, canvas)
// increment the counter and update the
text if player scores public void
onMouseClick(Location point) if (
hoop.contains(point) ) score score
2 display.setText("Your score is "
score )
- Note the conditional in onMouseClick()
- Note the use of constants for things that dont
change
39Next time Adding a Ball
- Next time, well add a ball to this
- Ball will move when we drag it in the hoop
- Program will have to check if you dragged the
ball in the hoop - How do we modify the code to do this?
- How to add the ball?
- How to check if the ball is in the hoop?
- Note thats not just where the mouse is!