Guest User

Untitled

a guest
Jul 17th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. /**
  2. Alice Lee
  3. Nov 2, 2009
  4. methods: public/private | returning or not (int void fraction)
  5. */
  6.  
  7. public class Fraction
  8. {
  9. private int num, den; // numerator and denominator
  10.  
  11. public Fraction () // constructor
  12. {
  13. num = 0;
  14. den = 1; // default statement, denominator cannot be 0
  15. }
  16.  
  17. public Fraction (int n, int d)
  18. {
  19. num = n;
  20.  
  21. if (d != 0)
  22. den = d;
  23.  
  24. else
  25. throw new IllegalArgumentException("Fraction cannot have 0 as denominator");
  26.  
  27. }
  28.  
  29. public Fraction (int n)
  30. {
  31. num = n;
  32. den = 1;
  33. }
  34.  
  35. public Fraction (Fraction n)
  36. {
  37. num = n.num; // pulling num on n > putting into num
  38. den = n.den;
  39. }
  40.  
  41. public Fraction fractionAdd (Fraction a)
  42. {
  43. {
  44. int newNom;
  45. int newDem;
  46. newNom = num * a.den + a.num * den;
  47. newDem = den * a.den;
  48. // System.out.print(newNom, newDem);
  49. return new Fraction(newNom, newDem);
  50. }
  51. }
  52.  
  53. private int gcf(int a, int b)
  54. {
  55. int d, e;
  56. e=a;
  57. d=b;
  58.  
  59.  
  60. if (a<0)
  61. e=-a;
  62. if (b<0)
  63. d=-b;
  64.  
  65.  
  66.  
  67. while (e!=d)
  68. {if (e>d)
  69. e=e-d;
  70. else
  71. d=d-e;
  72. }
  73. return d;
  74. }
  75.  
  76. public Fraction reduce()
  77. {
  78. int x = gcf(num,den);
  79. num = num/x;
  80. den = den/x;
  81.  
  82. return new Fraction(num, den);
  83. }
  84.  
  85. public void fractionPrint()
  86. {
  87. System.out.println(num + "/"+ den);
  88. }
  89.  
  90.  
  91. public Fraction fractionSubtract (Fraction a)
  92. {
  93. {
  94. int newNom;
  95. int newDem;
  96. newNom = (num * a.den) - (a.num * den);
  97. newDem = den * a.den;
  98. return new Fraction(newNom, newDem);
  99. }
  100. }
  101.  
  102.  
  103.  
  104.  
  105. public static void main (String[] args)
  106. {
  107. Fraction x = new Fraction(1,2);
  108. Fraction y = new Fraction(3,4);
  109. Fraction z = new Fraction(x.fractionAdd(y));
  110. //x.fractionAdd(y);
  111. x.fractionPrint();
  112. y.fractionPrint();
  113. z.fractionPrint();
  114. z = z.reduce();
  115. z.fractionPrint();
  116.  
  117. //y.fractionPrint();
  118. }
  119.  
  120.  
  121.  
  122.  
  123.  
  124. }
Add Comment
Please, Sign In to add comment