Rational Class completed.

This commit is contained in:
2026-04-29 00:19:28 +03:30
parent 6a01e43eb2
commit 40070448ba
+24 -32
View File
@@ -47,50 +47,42 @@ public class Rational {
} }
// COMPLETED - Static method: r1 + r2 // COMPLETED - Static method: r1 + r2
public static Rational add(Rational r1, Rational r2) { public static Rational add(Rational r1, Rational r2) {return r1.add(r2);}
return r1.add(r2);
}
// TODO: Instance method - this - other //TODO
// Formula: a/b - c/d = (a*d - c*b) / (b*d)
public Rational subtract(Rational other) { public Rational subtract(Rational other) {
// YOUR CODE HERE int newNumerator = this.numerator * other.denominator - other.numerator * this.denominator;
return null; // Remove this line when implemented int newDenominator = this.denominator * other.denominator;
return new Rational(newNumerator, newDenominator);
} }
// TODO: Static method - r1 - r2 //TODO
public static Rational subtract(Rational r1, Rational r2) { public static Rational subtract(Rational r1, Rational r2) {return r1.subtract(r2);}
// YOUR CODE HERE
return null; // Remove this line when implemented
}
// TODO: Instance method - this * other //TODO
// Formula: (a/b) * (c/d) = (a*c) / (b*d)
public Rational multiply(Rational other) { public Rational multiply(Rational other) {
// YOUR CODE HERE int newNumerator = this.numerator * other.numerator;
return null; // Remove this line when implemented int newDenominator = this.denominator * other.denominator;
return new Rational(newNumerator, newDenominator);
} }
// TODO: Static method - r1 * r2 //TODO
public static Rational multiply(Rational r1, Rational r2) { public static Rational multiply(Rational r1, Rational r2) {return r1.multiply(r2);}
// YOUR CODE HERE
return null; // Remove this line when implemented
}
// TODO: Instance method - this / other //TODO
// Formula: (a/b) ÷ (c/d) = (a*d) / (b*c)
public Rational divide(Rational other) { public Rational divide(Rational other) {
// YOUR CODE HERE if (other.numerator == 0) {
// HINT: Division is multiplication by reciprocal System.out.println("You can't divide a number by zero!");
// Don't forget to check if other.numerator is zero! return null;
return null; // Remove this line when implemented }
int newNumerator = this.numerator * other.denominator;
int newDenominator = this.denominator * other.numerator;
return new Rational(newNumerator, newDenominator);
} }
// TODO: Static method - r1 / r2 //TODO
public static Rational divide(Rational r1, Rational r2) { public static Rational divide(Rational r1, Rational r2) {return r1.divide(r2);}
// YOUR CODE HERE
return null; // Remove this line when implemented
}
// PROVIDED - String representation // PROVIDED - String representation
@Override @Override