and I don't understand why.
public class Rational{
public int numerator, denominator;
public Rational( int num, int den ) // This constructor takes two numbers and makes a fraction out of them
{
if (den!=0)
{
numerator = num;
denominator = den;
}
else
System.exit(0);
}
public Rational times( Rational that ) // This Method multiplies two fractions together
{
return new Rational( this.numerator * that.numerator, this.denominator * that.denominator );
}
public Rational dividedBy( Rational that)
{
return new Rational( this.numerator * that.denominator , this.denominator / that.numerator );
}
public Rational plus( Rational that)
{
return new Rational( (this.numerator * that.denominator) + (this.denominator * that.numerator), this.denominator*that.denominator);
}
public Rational minus( Rational that)
{
return new Rational( (this.numerator * that.denominator) - (this.denominator * that.numerator), this.denominator*that.denominator);
}
public void reduce() {
int num = Math.abs(numerator);
int den = Math.abs(denominator);
while (den != 0) {
int c = den;
den = num % den;
num = c;
}
int gcd = num;
numerator /= gcd;
denominator /= gcd;
}
}
public class RationalTester{
public static void main(String[] args)
{
Rational x = new Rational(6, 4); //This fraction is 6/4
Rational y = new Rational(5, 2); // This fraction is 5/2
Rational z = x.times(y); //This method multiplies the two fractions x and y and assigns the product to z
z.reduce(); // This method reduces the fraction z
System.out.println( x.toString() + " * " + y.toString() + " = " + z.toString() );
System.exit(0);
}
}

New Topic/Question
Reply




MultiQuote



|