Hello, I am having trouble trying to build the "gcd(Greatest common divisor". It's where if I input "1/2 - 3/4" output would be "-2/8", where I would want "-1/4". Here is my code. I finished all my arithmetic's, and now all I need to do is simplify my answers. After that, I should be good with this code. Any help is appreciated.
import java.util.Scanner; public class Rational { // TODO Auto-generated method stub //Data members private int numerator; private int denominator; //Constructors Rational() { numerator = 0; denominator = 1; } Rational(int num, int den) { numerator = num; denominator = den; } //Accessors public int getNumerator() { return numerator; } public int getDenominator() { return denominator; } // Modifiers public void setNumerator(int num) { numerator = num; } public void setDenominator(int den) { denominator = den; } public Rational inputRational(){ Scanner input = new Scanner(System.in); System.out.println("Enter numerator"); numerator = input.nextInt(); System.out.println("Enter Denominator"); denominator = input.nextInt(); return new Rational(numerator, denominator); } public String toString() { return numerator + "/" + denominator; } private static int gcd(int m, int n) { int r; while(n!= 0) { r = m % n; m = n; n = r; } return m; } //Adding public Rational add(Rational f) { int num; int den; num = (numerator * f.denominator) + (f.numerator * denominator); den = denominator * f.denominator; return new Rational(num, den); } public void sub(Rational f1, Rational f2) { numerator = (f1.numerator * f2.denominator) - (f2.numerator * f1.denominator); denominator = f1.denominator * f2.denominator; } public Rational mul(Rational f) { int num; int den; num = numerator * f.numerator; den = denominator * f.denominator; return new Rational(num, den); } public void div(Rational f1, Rational f2) { this.numerator = f1.numerator * f2.denominator; this.denominator = f1.denominator * f2.numerator; } public static double divided(Rational f1, Rational f2) { double value; value = (f1.numerator/f2.denominator)*(f2.denominator/f2.numerator); return value; } }
Here's my tester.
public class TestRational { public static void main(String[] args) { // TODO Auto-generated method stub Rational f1 = new Rational(); Rational f2 = new Rational(); Rational f3 = new Rational(); f1.inputRational(); f2.inputRational(); f3 = f1.add(f2); System.out.println(f1.toString() + " + " + f2.toString() + " = " + f3.toString()); f3.sub(f1,f2); System.out.println(f1.toString() + " - " + f2.toString() + " = " + f3.toString()); f3 = f1.mul(f2); System.out.println(f1.toString() + " * " + f2.toString() + " = " + f3.toString()); f3.div(f1, f2); System.out.println(f1.toString() + " / " + f2.toString() + " = " + f3.toString()); System.out.println(Rational.divided(f1,f2)); f1.setNumerator(2); f2.setDenominator(5); System.out.println("Numerator: " +f1.getNumerator()); System.out.println("Denominator: "+f2.getDenominator()); } }