Computer Science 15-100 (Sections T & U), Spring 2008
Class Notes:  Ch 4+5:  Classes, Methods, Conditionals, and Loops (2 of 3)


Logistics

  1. Schedule
    1. Hw5 due tomorrow
      Tonight's office hours to be announced in today's class
    2. Quiz 4 today
    3. Quiz 5 Tuesday (back to our regular schedule)
      1. Note:  Today's material will be included in quiz 5!
      2. May be on quiz 5:
        1. Chapters 1-3 (of course!) + Sections 4.1, 4.4, 5.1 (boolean expr's), 5.2 (if), 5.3, 5.5 (while), 5.8 (for), 5.9
      3. Will not be on quiz 5 (unless it appears in class notes):
        1. Section 4.2 (instance data), 4.3 (visibility/accessors), 4.5-4.9, 5.4 (switch), 5.6 (iterators), 5.7 (do), 5.10-5.12
    4. Bonus Lecture #1 on Tuesday
      1. Discuss times
  2. Reading:
    1. L&L Chapter 4:  Writing Classes
           Section 4.4 today
    2. L&L Chapter 5:  Conditionals and Loops
           Sections 5.1, 5.2., 5.3, 5.5, and 5.8 today

Topic Outline:

Style:  Test Cases + Boundary Cases

Methods, Conditionals, and Loops (Oh my!)

  1. Format of a Class with Static Methods:

    For now:  A class is a collection of static methods!
    We will add more to this definition very soon.
    Note that the order of the methods does not matter.

    class MyCode {
       public static void method1() {
          // ... //
       }

       public static void method2() {
          // ... //
       }

       // ... //

       public static void main(String[] args) {
          // ... //
       }
    }
     
  2. Boolean expressions
    a)  Equality and inequality operators (==, !=)
    b)  Relational Operators  (<, <=, >, >=)
    c)  Logical Operators (!, &&, ||)
    d)  Truth Tables and Logical Operators
    e)  Short-Circuit Evaluation
    class MyCode {
      public static boolean t() {
        System.out.print("T");
        return true;
      }
      public static boolean f() {
        System.out.print("F");
        return false;
      }
      public static void main(String[] args){
        System.out.println("AND:");
        System.out.println(t() && t()); // TTtrue
        System.out.println(t() && f()); // TFfalse
        System.out.println(f() && t()); // Ffalse
        System.out.println(f() && f()); // Ffalse
    
        System.out.println("OR:");
        System.out.println(t() || t()); // Ttrue
        System.out.println(t() || f()); // Ttrue
        System.out.println(f() || t()); // FTtrue
        System.out.println(f() || f()); // FFfalse
      }
    }
    
    f)  Using short-circuit evaluation as a "guard"
        // guard against division by zero
        if ((d != 0) && (n/d < 20))
    
        // guard against index out of bounds
        if ((i >= 0) && (i < s.length()) && (s.charAt(i) == 'z')) ...
  3. "if" Statements

    a)  The "if" statement
       if (1 < 2)
          System.out.println("yes");  // prints "yes"
    
       if (2 < 1)
          System.out.println("yes");  // does not get called!
    

    b)  Note:  A Block { ... } is a Statement!
    See If Statement syntax diagram on p. 218

       if (1 < 2) {
          System.out.println("yes");  // prints "yes"
       }
    
       // the block can include multiple statements:
       if (1 < 2) {
          System.out.println("yep");  // prints "yep"
          System.out.println("yep");  // prints "yep" again!
       }
    
       // the block can even include no statements (an empty block):
       if (1 < 2) {
          // do nothing    <- include this comment in any empty block
       }
    
    c)  Warning:  Indenting Doth Not Make A Block!
       if (2 < 1)
          System.out.println("yes");  // not called
          System.out.println("yep");  // prints "yep"
    
    d)  Warning:  A semicolon is also a Statement (the Empty Statement)
       if (2 < 1);
          System.out.println("yes");  // prints "yes"

          Safety Hint:  Do not use the empty statement.  Ever.
          If you must, use an empty block with a suitable comment like "do nothing" (see above).

    e)  The "if-else" statement

       if (2 < 1)
          System.out.println("yes");  // not called
       else
          System.out.println("no");   // prints "no" 

    f)  The "if-else-if-...-else" construct

       if (2 < 1)
          System.out.println("a");  // not called
       else if (3 < 1)
          System.out.println("b");  // not called 
       else if (4 == 4)
          System.out.println("c");  // prints "c" 
       else
          System.out.println("d");  // not called

    g)  Nested "if" statements

       if (2 < 1) {
          if (3 == 3)
            System.out.println("a");  // not called
          else
            System.out.println("b");  // not called
       }
       else {
          if (4 == 4)
            System.out.println("c");  // prints "c"
          else
            System.out.println("d");  // not called
       }

    h)  The "dangling-else" problem

       if (2 < 1)
          if (3 == 3)
            System.out.println("a");  // not called
       else
         System.out.println("b");  // not called
    

    Remedy:  use a block!

       if (2 < 1) {
          if (3 == 3)
            System.out.println("a");  // not called
       }
       else
         System.out.println("b");  // prints "b"
  4. Comparing Data

    a)  Comparing Floats and Doubles

    b)  Comparing Characters

    c)  Comparing Objects (== versus .equals())

    d)  Comparing Strings with compareTo()
     

  5. The "while" Statement
    See syntax diagram on p. 235

    a)  Simple Example
    class MyCode {
      public static void main(String[] args) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        int sum = 0;
        int x;
    
        System.out.print("Enter a # (0 to exit): ");
        x = scanner.nextInt();
    
        while (x != 0) {
            sum += x;
            System.out.println("Running sum = " + sum);
    
            System.out.print("Enter a # (0 to exit): ");
            x = scanner.nextInt();        
        }
       
        System.out.println("Final sum = " + sum);
      }
    }
    b)  Using Infinite Loops and Break Statements to Avoid Duplicate Code

    Notice the duplicate code in the example above.  These lines occur twice:  (Do you see why?)
        System.out.print("Enter a # (0 to exit): ");
        x = scanner.nextInt();

    We fix this as such:
    class MyCode {
      public static void main(String[] args) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        int sum = 0;
        int x;
    
        while (true) {
            System.out.print("Enter a # (0 to exit): ");
            x = scanner.nextInt();
    
            if (x == 0)
              break;
    
            sum += x;
            System.out.println("Running sum = " + sum);
        }
       
        System.out.println("Final sum = " + sum);
      }
    }
    c)  The continue statement
    class MyCode {
      public static void main(String[] args) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        int sum = 0;
        int x;
    
        while (true) {
            System.out.print("Enter a # (0 to exit): ");
            x = scanner.nextInt();
    
            if (x == 0)
              break;
    
            else if (x < 0) {
              System.out.println("Ignoring that negative value!");
              continue;
            }
    
            sum += x;
            System.out.println("Running sum = " + sum);
        }
       
        System.out.println("Final sum = " + sum);
      }
    }
  6. The "for" Statement
    See syntax diagram on p. 253

    Note:
      We covered the "for" loop basics already, both in class and on the homework.  We'll cover it in more detail next lecture.  Quiz 5 will only cover "simple" for loops.
     
  7. Nested Loops
    class MyCode {
      public static void main(String[] args) {
        int x, y;
        for (x=1; x<=4; x++) {
            for (y=1; y<=4; y++)
                System.out.print("(" + x + "," + y + ") ");
            System.out.println();
        }
      }
    }

    Output:

    (1,1) (1,2) (1,3) (1,4)
    (2,1) (2,2) (2,3) (2,4)
    (3,1) (3,2) (3,3) (3,4)
    (4,1) (4,2) (4,3) (4,4)

  • carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem