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


Logistics

  1. Schedule
    1. Hw6
      • Due Friday
    2. Quiz 5
      • Change of plans:  no quiz this week.  Quiz 5 is Tue, 26-Feb.
      • Consequence:  Quiz 5 covers more material (all of today's material is included).
    3. Bonus Lecture #1
      • Tonight (at 4:30 and again at 6:30) in 5304 Wean Hall
      • Come prepared to think, think, think!  Take good notes, too!
  2. Reading:
    1. L&L Chapter 4:  Writing Classes  (just static methods; no instance data, instance methods, encapsulation, or constructors)
      L&L Chapter 5:  Conditionals and Loops

Topic Outline:

Style for hw6:

Methods, Conditionals, and Loops (Oh my!)

  1. The Conditional Operator (?:)
  2. Switch Statement
    See syntax diagram on p. 232
  3. The "do" Statement
    See syntax diagram on p. 250
  4. The "for" Statement
    See syntax diagram on p. 253
     
  5. Iterators
    1. Support iterating over arbitrary collections
       
    2. Key methods:  hasNext and next
       
    3. Ex 1:  Reading strings from the user:
      java.util.Scanner scanner = new java.util.Scanner(System.in);
      while (scanner.hasNext()) {
         String s = scanner.next();
         System.out.println("read string: " + s);
      }
       
    4. Ex 2:  Reading strings from within a string (eg, portions of phone number):
      String phoneNumber = "44-0-20-7321-2233"; // Buckingham Palace
      java.util.Scanner scanner = new java.util.Scanner(phoneNumber);
      scanner.useDelimiter("-");
      while (scanner.hasNext()) {
         String s = scanner.next();
         System.out.println(s); // prints 44, then 0, then 20, then 7321, then 2233
      }

        
  6. Block scope of variables
    1. Local variables (including parameters) are only visible within the block they are declared.
      So:  Local variables are not visible outside the block they are declared.
      for (int x=0; x<2; x++) {
        System.out.println(x);  // prints 0 then 1
      }
      System.out.println(x);  // will not compile, x is not in scope here!

       
    2. Local variables are only visible from their definitions onward
      public static void main(String[] args) {
        System.out.println(x);  // will not compile, x is not in scope here!

        int x = 3;
        System.out.println(x); // would print 3, if this compiled
      }
       
    3. You can reuse the same-named local variable in different blocks
      for (int x=0; x<2; x++) {
        System.out.println(x);  // prints 0 then 1
      }
      for (int x=0; x<2; x++) {
        System.out.println(x);  // prints 0 then 1 again
      }

       
    4. Style Alert:  bad idea #2541:  use a block as a statement to reuse same-named local variables
      public static void main(String[] args) {
        {
            int x = 3;
            System.out.println(x); // prints 3
        }
        {
            int x = 4;
            System.out.println(x); // prints 4
        }
      }

Practice:  Methods, Conditionals, and Loops (Oh my!)

Quiz 4 Redux:

// Quiz4.java
// <Your name, andrew id, section>

// This is a computer-based programming quiz.
// You MAY (in fact, MUST) use DrJava to write this quiz.
// You MAY NOT use the internet (except to obtain the quiz and submit it),
// or ANY OTHER PROGRAMS on the computer.  Or any notes.  Or any person
// (besides yourself).

// When you are done with your quiz, EMAIL THE FILE Quiz4.java to koz AT cmu.edu
// Email it as BOTH an ATTACHMENT and PASTED INTO THE BODY of the one message.
// CC yourself, and verify that you received the message you sent.
// Be SURE to email the Java file and NOT THE CLASS FILE!!!

// Style does not count on quizzes. Only correctness.

// IMPORTANT NOTE:  YOU MAY NOT "HARDCODE" THE TEST DATA INTO YOUR ANSWER!!!!
// Your solutions must work in general, and not just for the given test cases.

// You have 30 minutes.  Good luck.

public class Quiz4 {

  ///////////////////////////////////////////////////////////
  ///// PART 1:  Reverse Strings
  ///////////////////////////////////////////////////////////

  // PROBLEM STATEMENT:
  // Write a method that takes two possibly-null strings and returns true if
  // each string is the exact REVERSE of the other, taking case,
  // whitespace, and punctuation into account, and false otherwise.
  // NOTE:  The only String methods you may use are length and charAt.
  // Your method should work like this:
  //     areReverseStrings("abc","cba") returns true
  //     areReverseStrings("Abc","cba") returns false
  //     areReverseStrings("abc!","cba") returns false
  //     areReverseStrings(null,"abc") returns false (does not crash!)
  // Note: your program must work for the null string, which is not a string,
  // so is not the reverse of any string.  So just return false in that case!
  
  public static boolean areReverseStrings(String s1, String s2) {
    return false;  // REPLACE THIS WITH YOUR ANSWER!
  }
  
  public static void testAreReversedStrings() {
    System.out.println("Testing areReversedStrings...");
    verify(areReverseStrings("abc" ,"cba") == true);
    verify(areReverseStrings("Abc" ,"cba") == false);
    verify(areReverseStrings("abc!","cba") == false);
    verify(areReverseStrings(null  ,"abc") == false); // does not crash!
    System.out.println("  Passed these tests (though we will use more tests when grading)");
  }

  ///////////////////////////////////////////////////////////
  ///// PART 2:  Formatted Addition
  ///////////////////////////////////////////////////////////

  // PROBLEM STATEMENT:
  // Write a method that takes two doubles, each in the range [0,10),
  // and returns a single String that contains a nicely formatted
  // addition problem and its solution where all values are rounded
  // to the nearest 10th, all decimal points align, the second line
  // has a preceding "+" sign and a space, and the third line
  // contains 3 right-aligned dashes.
  
  // For example, if the method is called with the values 2.3 and 3.5,
  // it would return a string that, when printed out, would display:
  //   2.3
  // + 3.5
  //   ---
  //   5.8
  // This is all stored in one string, though, with newlines (\n's),
  // as such:
  // "  2.3\n+ 3.5\n  ---\n  5.8"
  
  // If either variable is less than 0 or greater than or equal to 10,
  // you should just return the string "out of range".
  
  // Also:  you should round the parameters BEFORE adding, and then
  // round the sum AFTER adding.  So if the parameters are 1.05 and
  // 2.05, you would first round these to 1.1 and 2.1, which sum to 3.2.
  // (Note that 1.05 + 2.05 = 3.1 if we do not first round the parameters.)
  // The only reason to round the result is to handle round-off error.
  
  // Thus, your method should work like this:
  // makeAdditionProblem(2.3 ,3.5 ) returns "  2.3\n+ 3.5\n  ---\n  5.8"
  // makeAdditionProblem(1.05,2.05) returns "  1.1\n+ 2.1\n  ---\n  3.2"
  // makeAdditionProblem(-1,3) returns "out of range"
  
  // HINT: You'll probably want to use String.format here -- it does
  // rounding and right-aligning for you!
  
  public static String makeAdditionProblem(double d1, double d2) {
    return "to do!"; // REPLACE THIS WITH YOUR ANSWER!
  }
  
  public static void testMakeAdditionProblem() {
    System.out.println("Testing makeAdditionProblem...");
    verify(makeAdditionProblem(2.3 ,3.5 ).equals("  2.3\n+ 3.5\n  ---\n  5.8"));
    verify(makeAdditionProblem(1.05,2.05).equals("  1.1\n+ 2.1\n  ---\n  3.2"));
    verify(makeAdditionProblem(-1,3).equals("out of range"));
    System.out.println("  Passed these tests (though we will use more tests when grading)");
  }

  ///////////////////////////////////////////////////////////
  ///// PART 3:  Sum of the first N Terms of the series
  /////          S = 4/1 - 4/3 + 4/5 - 4/7 +...
  ///////////////////////////////////////////////////////////

  // PROBLEM STATEMENT:
  // Consider this series:
  //  S = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 - ...
  // The first term is 4/1.  The second term is -4/3.  And so on.
  // As you can see, the sign (+/-) of each term changes, the numerator of each
  // term is 4, and the denominator keeps increasing by 2.

  // Write a method that takes an int "n" and if n is positive, returns the
  // sum of the first n terms of this series, rounded to the nearest 100th,
  // returning -1 if n is non-positive.  It should work like this:
  //   sumOfFirstNTerms(1) returns 4.00 (which is 4/1 when rounded)
  //   sumOfFirstNTerms(2) returns 2.67 (which is 4/1 - 4/3 when rounded)
  //   sumOfFirstNTerms(3) returns 3.47 (which is 4/1 - 4/3 + 4/5 when rounded)
  //   sumOfFirstNTerms(4) returns 2.90 (which is 4/1 - 4/3 + 4/5 - 4/7 when rounded)

  // Interesting aside:
  // As n gets larger, sumOfFirstNTerms(n) approaches pi (3.14).  Wow!

  public static double sumOfFirstNTerms(int n) {
    return 42;  // REPLACE THIS WITH YOUR ANSWER!
  }
  
  public static void testSumOfFirstNTerms() {
    System.out.println("Testing sumOfFirstNTerms...");
    verify(almostEqual(sumOfFirstNTerms(0),-1));
    verify(almostEqual(sumOfFirstNTerms(1),4.00));
    verify(almostEqual(sumOfFirstNTerms(2),2.67));
    verify(almostEqual(sumOfFirstNTerms(3),3.47));
    verify(almostEqual(sumOfFirstNTerms(4),2.90));
    System.out.println("  Passed these tests (though we will use more tests when grading)");
  }

  ///////////////////////////////////////////////////////////
  ///// Supporting Code  (verify, almostEqual, main)
  ///////////////////////////////////////////////////////////
  
  public static boolean almostEqual(double d1, double d2) {
    double epsilon = 0.0000001; // adjust as appropriate
    return Math.abs(d2 - d1) < epsilon;
  }
  
  public static void verify(boolean test) {
    if (test == false) throw new RuntimeException("Failed verify test!");
  }

  public static void main(String[] args){
    testAreReversedStrings();
    testMakeAdditionProblem();
    testSumOfFirstNTerms();
  }
}

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