teaching machines

CS 145 Lecture 8 – Generous Methods

September 19, 2014 by . Filed under cs145, fall 2014, lectures.

Agenda

TODO

Program This 1

Program This 2

  1. Write a method that returns the slope of a line passing between two points.
  2. Write a method that returns the y-intercept of a line passing between two points.

Code

Mailing.java

package lecture0919;

public class Mailing {
  public static void main(String[] args) {
    labelMaker("name", "streetAddress", "city", "state", "zip");
    labelMaker("Department of Computer Science", "105 Garfield Ave.", "Eau Claire", "WI", "54702");
    labelMaker("FBI", "935 Pennsylvania Ave.", "Washington", "DC", "20535");
    labelMaker("National Foundation for Celiac Awareness", "PO Box 544", "Ambler", "PA", "19002-0544");
  }
  
  public static void labelMaker(String name,
                                String streetAddress,
                                String city,
                                String state,
                                String zipCode) {
    System.out.println(name + "," + 
                       streetAddress + "," +
                       city + "," + 
                       state + "," + 
                       zipCode);
  }
}

RandomLetter.java

package lecture0919;

  import java.util.Random;
  
  public class RandomLetter {
    public static void main(String[] args) {
      char letter = getRandomLetter();
      // System.out.println((char) ((getRandomLetter() + getRandomLetter()) / 2));
      System.out.println(getRandomLetter());
    }
  
    public static char getRandomLetter() {
      // return (char) (g.nextInt(26) + 'a');
  
      String alphabet = "abcdefghijklmnopqrstuvwxyz";
      Random g = new Random();
      int index = g.nextInt(alphabet.length());
      char c = alphabet.charAt(index);
      return c;
    }
  }

Line.java

package lecture0919;

public class Line {
  public static void main(String[] args) {
//    System.out.println(getSlope(5, 3, 7, 8));
    System.out.println(getEquation(5, 3, 7, 8));
  }
  
  public static double getSlope(double x1,
                                double y1,
                                double x2,
                                double y2) {
    return (y2 - y1) / (x2 - x1);
  }
  
  public static double getIntercept(double x1,
                                    double y1,
                                    double x2,
                                    double y2) {
    double slope = getSlope(x1, y1, x2, y2);
    double intercept = y1 - slope * x1;
    return intercept;
  }
  
  public static String getEquation(double x1,
                                   double y1,
                                   double x2,
                                   double y2) {
    return "y = " + getSlope(x1, y1, x2, y2) + " * x + " + getIntercept(x1, y1, x2, y2);
  }
}

Haiku