Lecture 7, CS 302-6, September 19

  1. Review
    1. Arithmetic
    2. Random numbers
    3. Strings
  2. Strings
    1. Open Java API
    2. Strings are sequences of characters.
    3. String length

                                                               i.      theString.length()

    1. Empty String – “”.  Length 0
    2. Concatenating strings
    3. Reading String input
    4. Parsing numbers from strings
    5. Escape sequences
    6. theString.charAt()
    7. Substrings
    8. Java API

                                                               i.      http://download.oracle.com/javase/6/docs/api/

    1. Example-EasyCipher.java
  1. Chapter 3 – Decisions
    1. In other words, logic.  We want to be able to do different things depending on different inputs, etc
    2. Hamlet - To be, or not to be, that is the question:

Whether 'tis nobler in the mind to suffer

The slings and arrows of outrageous fortune,

Or to take arms against a sea of troubles,

And by opposing end them?

->If I am then:

      Suffer the slings and…

Else:

      Take arms…

  1. If statements
    1. If, else
    2. Syntax:

 if (condition)

{

do this;

}

else

{

do that;

}

    1. A few notes:

                                                               i.       {}

1.      Not necessary if there is only one line after, but good form

                                                             ii.      There is no semicolon after if/else

    1. block-structured code

                                                               i.      Indentation is not an accident – it helps us keep track of which parts of our programs go together

    1. Avoid redundant code

                                                               i.      If(){do this1; do this2;} else {do that; do this2;} - > move do this2; below

    1. Example – NumberGame.java
  1. Comparisons
    1. We were doing something above - > Relational operators
    2. >, >=, < , <=, ==,!=

                                                               i.      Note difference between = and ==

1.      = assigns, == tests equality

                                                             ii.      != means not equal to

  1. Nested Branches
    1. If/Elses within If/Elses
    2. Maintain block structure
    3. Example – Think of your class schedule:

                                                               i.      If day==Monday then if time is in 11:00-11:50, you are in CS.  If time==12-1, I have office hours.  Otherwise, if the day==Tuesday…

  1. Multiple Alternatives
    1. Up to this point, only have allowed two possibilities
    2. We can test more than two cases using ‘else if’.  So, we can get trees like the following, using nesting and multiple alternatives:

if(a==b)

{

      if(a==2)

{

            ~

}

else

{

            ~

}

}

else if(a>b)

{

      ~

}

else

{

      ~

}

  1. HW
    1. Finish reading Chapter 3