ADT fraction

I'm new to Java and I'm trying to create an ADT. My ADT involves creating and processing fractions through input of a numerator and denominator. I want one of my methods to add two fractions together and return a simplified fraction based on the gcd of the two sums. The problem I'm having is with instantiating the components of the two fractions(the numerator and denominator). The method should take a fraction other, denoted public Rational add(Rational other). The first variables I assigned were

int d1 = this.denominator;
int d2 = other.denominator;

but this doesn't seem to work. Below is the method thus far:

public Rational add(Rational other){
  int d1 = this.denominator;
  int d2 = other.denominator;
  int dtotal = d1*d2;
  int n1 = this.numerator*d2;
  int n2 = other.numerator*d1;
  int ntotal = n1+n2;
  if(ntotal>dtotal){
    for(int i=1; i<=ntotal; i++){
      if(ntotal%i==0 && dtotal%i==0){
        gcd=i;
      }
    }
  }else if(dtotal>ntotal){
    for(int i=1;i<=dtotal;i++){
      if(dtotal%i==0 && ntotal%i==0){
        gcd=i;
      }
    }
  }else if(dtotal==ntotal){
    gcd=numerator;
  }
  numerator = ntotal/gcd;
  denominator = dtotal/gcd;
}
(sumber) https://stackoverflow.com/

 

Artikel Selanjutnya Artikel Sebelumnya
Post Terkait :
Struktur Data