Fraction
We started writing a Fraction
class to represent fractional values
public class Fraction {
private long num; // numerator
private long den; // denominator
public Fraction (long numerator, long denominator) {
num = numerator;
den = denominator;
}
// Fraction g, Fraction h then g.add(h) returns "g + h"
public Fraction add (Fraction f) {
// (a / b) + (c / d) = (a * d + b * c) / b * d
long newNum = num * f.den + den * f.num;
long newDen = den * f.den;
return new Fraction(newNum, newDen);
}
// compute the greatest common divisor of two longs
public static long gcd (long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}
Improving and testing the implementation
double
String
BadArithmetic
from last weekWe can design objects that do better arithmetic!
What does the following code do?
int a = 10;
int b = 5;
b = a;
a = 20;
What are the values of a
and b
at the end of the execution?
Consider the method
void setValue (int a, int value) {
a = value;
}
What is the result of
a = 20;
setValue(a, 0);
What is the value of a
at the end of the execution?
Consider the following simple class
class Number {
public int value;
Number (int val) {
value = val;
}
}
What does the following code do?
Number aNum = new Number(10);
Number bNum = new Number(5);
bNum = aNum;
aNum.value = 20;
What are the values of a
and b
at the end of the execution?
Consider the method
void setNumberValue (Number a, int value) {
a.value = value;
}
What is the result of
setNumberValue(aNum, 0);
What is the value of aNum.value
at the end of the execution?