Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- Alice Lee
- Nov 2, 2009
- methods: public/private | returning or not (int void fraction)
- */
- public class Fraction
- {
- private int num, den; // numerator and denominator
- public Fraction () // constructor
- {
- num = 0;
- den = 1; // default statement, denominator cannot be 0
- }
- public Fraction (int n, int d)
- {
- num = n;
- if (d != 0)
- den = d;
- else
- throw new IllegalArgumentException("Fraction cannot have 0 as denominator");
- }
- public Fraction (int n)
- {
- num = n;
- den = 1;
- }
- public Fraction (Fraction n)
- {
- num = n.num; // pulling num on n > putting into num
- den = n.den;
- }
- public Fraction fractionAdd (Fraction a)
- {
- {
- int newNom;
- int newDem;
- newNom = num * a.den + a.num * den;
- newDem = den * a.den;
- // System.out.print(newNom, newDem);
- return new Fraction(newNom, newDem);
- }
- }
- private int gcf(int a, int b)
- {
- int d, e;
- e=a;
- d=b;
- if (a<0)
- e=-a;
- if (b<0)
- d=-b;
- while (e!=d)
- {if (e>d)
- e=e-d;
- else
- d=d-e;
- }
- return d;
- }
- public Fraction reduce()
- {
- int x = gcf(num,den);
- num = num/x;
- den = den/x;
- return new Fraction(num, den);
- }
- public void fractionPrint()
- {
- System.out.println(num + "/"+ den);
- }
- public Fraction fractionSubtract (Fraction a)
- {
- {
- int newNom;
- int newDem;
- newNom = (num * a.den) - (a.num * den);
- newDem = den * a.den;
- return new Fraction(newNom, newDem);
- }
- }
- public static void main (String[] args)
- {
- Fraction x = new Fraction(1,2);
- Fraction y = new Fraction(3,4);
- Fraction z = new Fraction(x.fractionAdd(y));
- //x.fractionAdd(y);
- x.fractionPrint();
- y.fractionPrint();
- z.fractionPrint();
- z = z.reduce();
- z.fractionPrint();
- //y.fractionPrint();
- }
- }
Add Comment
Please, Sign In to add comment