Algorithms and OOD (CSC 207 2014F) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] - [Learning Outcomes] [FAQ] [Teaching & Learning] [Grading] [Rubric] - [Calendar]
Current: [Assignment] [EBoard] [Lab] [Outline] [Reading]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines] [Readings]
Reference: [Student-Curated Resources] [Java 8 API] [Java 8 Tutorials] [Code Conventions]
Related Courses: [CSC 152 2006S (Rebelsky)] [CSC 207 2014S (Rebelsky)] [CSC 207 2014F (Walker)] [CSC 207 2011S (Weinman)]
Misc: [Submit Questions] - [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] - [Issue Tracker (Course)] [Issue Tracker (Textbook)]
Overview
6 * 7this to refer to the implicit object
(at least in Java).For multiply, we'll expect to write
public class Fraction
{
BigInteger num;
BigInteger denom;
public Fraction add(Fraction that)
{
// a/b + c/d = (ad+bc)/bd
BigInteger resultNumerator =
this.num.multiply(that.denom).add(this.denom.multiply(that.num));
BigInteger resultDenominator =
this.denom.multiply(that.denom);
return new Fraction(resultNumerator, resultDenominator);
} // add(Fraction)
} // class Fraction
Java has a huge collection of built-in classes.
new? Because we're building a new object,
rather than modifying the current one.
new ClassName(Parameters)m_?
What might be wrong with this code?
public class Fraction
{
BigInteger num;
BigInteger denom;
public Fraction(BigInteger num, BigInteger denom)
throws ZeroDenominatorException
{
this.num = num;
this.denom = denom;
} // Fraction(BigInteger, BigInteger)
public Fraction add(Fraction that)
{
// a/b + c/d = (ad+bc)/bd
BigInteger resultNumerator =
this.num.multiply(that.denom).add(this.denom.multiply(that.num));
BigInteger resultDenominator =
this.denom.multiply(that.denom);
return new Fraction(resultNumerator, resultDenominator);
} // add(Fraction)
} // class Fraction
Writing gcd
this (Unfortunately, we want something
more general)Maybe one parameter: The other value (implicit: this
class BigInteger { public BigInteger gcd(BigInteger that) { } }
We don't even have to write it! Yay!
Code!
public Fraction add(Fraction that)
{
// a/b + c/d = (ad+bc)/bd
BigInteger resultNumerator =
this.num.multiply(that.denom).add(this.denom.multiply(that.num));
BigInteger resultDenominator =
this.denom.multiply(that.denom);
BigInteger gcd = resultNumerator.gcd(resultDenominator);
resultNumerator = resultNumerator.divide(gcd);
resultDenominator = resultDenominator.divide(gcd);
return new Fraction(resultNumerator, resultDenominator);
} // add(Fraction)
Improving: