Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Rational {
- // Creating instance variables for the numerator and denominator
- private long numerator;
- private long denominator;
- // Constructor that creates a new Rational object, making sure the denominator is not 0 or negative.
- public Rational (long numer, long denom){
- if (denom == 0){
- throw new RuntimeException("Error, can't have a denominator of 0.");
- }
- if (denom <0){
- denom = -denom;
- numer = -numer;
- }
- long greatestCommonDivisor = gcd(numer, denom);
- numerator = numer / greatestCommonDivisor;
- denominator = denom / greatestCommonDivisor;
- }
- // This method takes two rational numbers and adds them together
- public Rational plus(Rational b){
- Rational answer = new Rational (this.numerator * b.denominator + b.numerator * this.denominator, b.denominator * this.denominator);
- return answer;
- }
- //This method takes two rational numbers and subtracts them
- public Rational minus (Rational b){
- Rational answer = new Rational (this.numerator * b.denominator - b.numerator * this.denominator, b.denominator * this.denominator);
- return answer;
- }
- //This method takes two rational numbers and multiplies them
- public Rational times (Rational b){
- Rational answer = new Rational (this.numerator * b.numerator, this.denominator * b.denominator);
- return answer;
- }
- // This method uses Euclid's algorithm which calculates the greatest common divisor
- public static long gcd(long p, long q){
- if (q==0) return p;
- long r = p % q;
- return gcd(q, r);
- }
- // This method produces a string representation of values
- public String toString(){
- if (denominator == 1)
- return numerator + "";
- else
- return numerator + "/" + denominator;
- }
- // Test client
- public static void main (String args[]){
- Rational p = new Rational (1, 6);
- Rational q = new Rational (4, 8);
- Rational r = p.minus(q);
- System.out.println(r);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement