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;
}
You need to define your interface outside of the class with the required methods. Here is the sample, please edit as per your needs.
interface Rational {
public int getNumerator();
public int getDenominator();
public Rational add(Rational other);
public Rational multiply(Rational other);
public int compareTo(Rational other);
}
Now your class should be defined like this:
public class RationalC implements Rational {
int gcd;
int numerator;
int denominator;
@Override
public int getNumerator() {
return numerator;
}
@Override
public int getDenominator() {
return denominator;
}
@Override
public Rational add(Rational other) {
return null;
}
@Override
public Rational multiply(Rational other) {
return null;
}
@Override
public int compareTo(Rational other) {
return 0;
}
}
Add your add
, multiply
method definition. Use the getNumerator()
and getDenominator()
to access the values instead of directly accessing them.