CS 145 Lecture 8 – Generous Methods
September 19, 2014 by Chris Johnson. Filed under cs145, fall 2014, lectures.
Agenda
TODO
- Start homework 2. Due before October 2.
Program This 1
- Write a Java method that prints the data used to generate a mailing label. What data is needed? How can you make the method reusable? Separate each datum by a comma.
Program This 2
- Write a method that returns the slope of a line passing between two points.
- 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