Lecture 8, CS 302-7 and 8, February 8

 

  1. Reminders
    1. Piazza

                                                               i.      http://pages.cs.wisc.edu/~cs302/?r=piazza

  1. Review
    1. Strings

                                                               i.      Escape sequences

    1. Decisions

                                                               i.      If

1.      One or none

                                                             ii.      If/else

1.      One or another

    1. Comparisons
  1. Comparisons
    1. Relational operators
    2. >, >=, < , <=, ==,!=

                                                               i.      Note difference between = and ==

1.      = assigns, == tests equality

    1. ints: test equality with ==
    2. String: test equality with <String 1>.equals(<String 2>);
    3. Floating point (double) comparisons

                                                               i.      rule of thumb – be careful

                                                             ii.      epsilon – see textbook

  1. Multiple alternatives with if/else
    1. Up to this point, we only have allowed two possibilities
    2. Else if

                                                               i.      One of many

if (<cond 1>){

      //Do something

}

else if (<cond 2>){

      //Do something else

else {

      //Do a third thing

}

  1. Nested Branches
    1. If/Elses within If/Elses - conditionals within conditionals
    2. Block structured code

if (<cond 1>){

      //Do something

      if (<cond 2>){

      //Do something else

else {

      //Do a third thing

      }

}

    1. Example – Birthday2.java
  1. Switch statement
    1. Consider situation:

                                                               i.      Month names in birthday program

                                                             ii.      If month==1, January…etc

    1. Switch statements give us another way for writing long chains of if/elses
    2. Only ints/chars in the switch condition
    3. Only == for comparisons; no >, etc
    4. Structure:

switch (digit)

{

      case <num1>:  //Something; break;

case <num2>: //Something else; break;

default: ~; break;

}

    1. Note – if break; missing, continues with next statement
    2. Update Birthday2.java
  1. Assorted Topics:
    1. Dangling else

if(a)

   if(b)

else

    1. Which if() does the else go with?

                                                               i.      Answer – the second one.

                                                             ii.      Better answer – avoid the ambiguity by using {} appropriately

  1. Booleans
    1. For storing whether a logical condition is true or false.
    2. Possible values: true, false

boolean t=true;  boolean f=false;

  1. HW
    1. Finish reading ch. 3