Lecture 8, CS 302-7 and 8, February 8
- Reminders
- Piazza
i.
http://pages.cs.wisc.edu/~cs302/?r=piazza
- Review
- Strings
i.
Escape sequences
- Decisions
i.
If
1.
One or none
ii.
If/else
1.
One or another
- Comparisons
- Comparisons
- Relational
operators
- >,
>=, < , <=, ==,!=
i.
Note difference between = and ==
1.
= assigns, == tests equality
- ints:
test equality with ==
- String:
test equality with <String 1>.equals(<String 2>);
- Floating
point (double) comparisons
i.
rule of thumb – be careful
ii.
epsilon – see textbook
- Multiple
alternatives with if/else
- Up
to this point, we only have allowed two possibilities
- Else
if
i.
One of many
if (<cond 1>){
//Do
something
}
else if (<cond 2>){
//Do
something else
else {
//Do
a third thing
}
- Nested
Branches
- If/Elses
within If/Elses - conditionals within conditionals
- Block
structured code
if (<cond 1>){
//Do
something
if
(<cond 2>){
//Do
something else
else {
//Do
a third thing
}
}
- Example
– Birthday2.java
- Switch
statement
- Consider
situation:
i.
Month names in birthday program
ii.
If month==1, January…etc
- Switch
statements give us another way for writing long chains of if/elses
- Only
ints/chars in the switch condition
- Only
== for comparisons; no >, etc
- Structure:
switch (digit)
{
case
<num1>: //Something; break;
case
<num2>: //Something else; break;
…
default: ~;
break;
}
- Note
– if break; missing, continues with next statement
- Update
Birthday2.java
- Assorted
Topics:
- Dangling
else
if(a)
if(b)
else
- Which
if() does the else go with?
i.
Answer – the second one.
ii.
Better answer – avoid the ambiguity by using {} appropriately
- Booleans
- For
storing whether a logical condition is true or false.
- Possible
values: true, false
boolean t=true; boolean f=false;
- HW
- Finish
reading ch. 3