Lecture 16, CS 302-6, October 10
- Review
- Methods
i.
As black box
1.
Something I’d like to emphasize: Methods do ONE thing
ii.
Declaring, Using
iii.
Parameters/arguments, return values
iv.
Fyi:
http://99-bottles-of-beer.net/
- Void
methods
- Declare
method as ‘void’ (instead of return type)
i.
For instance, main method
ii.
Other examples – methods that just print things, etc
- End
with return; or just with }
i.
Neither is really better/preferred
- Can
still have return; in the middle to exit early
- Using
void methods: method(); (not something=method();)
- Example
– Drawer.java
- Technical
details of parameters
- Parameter
‘variable’ and parameter ‘value’
- Pass
by value, not reference
i.
Changing a value in a method does not change the value in the
method that called it
- Variable
names in separate blocks are separate
- More
on return statements
- Can
return literals, variables, expressions, etc…
- Immediately
exits the method call
- You
can use return; at different points in a method call
i.
Example – safe divide method.
Return early if /0. Else perform
divide
- Watch
out for – unreachable code, branches without returns
- Watch
out for – make sure to STORE return value, not just compute it.
i.
dollars=addInterest(dollars);
- Stepwise
refinement
- Think
of your program as a sort of flowchart – you want to think of each
possible case, and what happens after it
- http://xkcd.com/627/
i.
Each square is a method.
Each diamond is a condition. The
lines are branches
- Example
– LeapYear.java (not finished yet)
i.
Via stepwise refinement – think about each possible case
ii.
Begin by describing conditions for leap year
- HW
- Read
5.6-5.7