Computer Science 15-100 (Sections T & U), Spring 2008
Class Notes: Writing Classes (Day 2)
Logistics
Topic Outline:
Varargs: Variable-length arguments as arrays
public static void main(String[] args) throws Exception {
System.out.println(max(1,3,5,7,6,4,2));
}
public static int max(int... a) {
if (a.length == 0) return 0;
int max = a[0];
for (int i=1; i<a.length; i++) max = Math.max(max,a[i]);
return max;
}
We will start with our simple Fraction class (from
last lecture)
(Note that the new state of our code from the end of class, demonstrating the
concepts from today's lecture, is appended below.)
Here is our code at the end of class:
public class FractionExample {
public static java.util.Scanner scanner = new java.util.Scanner(System.in);
public static java.util.Random random = new java.util.Random();
public static void main(String[] args) {
Fraction x = new Fraction(2,7);
Fraction y = new Fraction(3,7);
System.out.println("x = " + x);
System.out.println("y = " + y);
Fraction z = x.times(y);
System.out.println("z = " + z);
System.out.println("z's numerator is: " + z.getNum());
z.setNum(z.getNum() + 1);
System.out.println("z = " + z);
}
}
class Fraction {
// instance properties
// instance == object
// properties == variables == fields == attributes
private int num = 10, den;
// accessors
public int getNum() {
return this.num;
}
public int getDen() {
return this.den;
}
// mutators
public void setNum(int num) {
this.num = num;
reduce();
}
public void setDen(int den) {
this.den = den;
reduce();
}
private static int gcd(int i1, int i2) {
int gcd = 1;
for (int i=2; i<=Math.min(i1,i2); i++)
if ((i1 % i == 0) && (i2 % i == 0)) gcd = i;
return gcd;
}
public Fraction(int num, int den) {
// System.out.println("make a fraction with n = " + n + " and d = " + d);
this.num = num;
this.den = den;
reduce();
}
private void reduce() {
int gcd = gcd(this.num,this.den);
this.num = this.num / gcd;
this.den = this.den / gcd;
}
// this that
// (a/b) + (c/d) == ((ad + bc) / (bd))
public Fraction plus(Fraction that) {
int n = ((this.num * that.den) + (this.den * that.num));
int d = (this.den * that.den);
return new Fraction(n,d);
}
public Fraction times(Fraction that) {
int n = this.num * that.num;
int d = this.den * that.den;
return new Fraction(n,d);
}
public Fraction pow(int p) {
int n = 1;
int d = 1;
for (int power=1; power<=p; power++) {
n *= this.num;
d *= this.den;
}
return new Fraction(n,d);
}
public String toString() {
return "" + num + "/" + den;
}
}
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem