Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. import java.util.*;
  2. public class Fraction {
  3. /**
  4. * declare attributes here
  5. */
  6. int numerator;
  7. int denominator;
  8.  
  9. /**
  10. * declare constructor here
  11. */
  12.  
  13. public Fraction(int numerator, int denominator){
  14. this.numerator = numerator;
  15. this.denominator = denominator;
  16. }
  17. /**
  18. * methods
  19. */
  20. private int gcd(int a, int b) {
  21. int temp;
  22. while (b!=0){
  23. temp = a % b;
  24. a = b;
  25. b = temp;
  26. }
  27. return a;
  28. }
  29. public int getNumerator(){
  30. return numerator;
  31. }
  32. public int getDenominator(){
  33. return denominator;
  34. }
  35. public void setNumerator(int number){
  36. numerator = number;
  37. }
  38. public void setDenominator(int number){
  39. denominator=number;
  40. }
  41. public Fraction reduce(){
  42. int n = gcd(numerator, denominator);
  43. numerator /=n;
  44. denominator /=n;
  45. return this;
  46.  
  47. }
  48. // add
  49. public Fraction add(Fraction other) {
  50. int newNum = (this.numerator*other.denominator + this.denominator*other.numerator);
  51. int newDeno= this.denominator*other.denominator;
  52. this.numerator = newNum;
  53. this.denominator=newDeno;
  54. this.reduce();
  55. return this;
  56. }
  57.  
  58. //subtract
  59. public Fraction subtract(Fraction other) {
  60. int newNum = (this.numerator*other.denominator - this.denominator*other.numerator);
  61. int newDeno= this.denominator*other.denominator;
  62. this.numerator = newNum;
  63. this.denominator=newDeno;
  64. this.reduce();
  65. return this;
  66. }
  67.  
  68. // multiple
  69. public Fraction multiply(Fraction other) {
  70. int newNum = (this.numerator*other.numerator);
  71. int newDeno= this.denominator*other.denominator;
  72. this.numerator = newNum;
  73. this.denominator=newDeno;
  74. this.reduce();
  75. return this;
  76. }
  77.  
  78. // divide
  79. public Fraction divide(Fraction other) {
  80. int newNum = (this.numerator*other.denominator);
  81. int newDeno= this.denominator*other.numerator;
  82. this.numerator = newNum;
  83. this.denominator=newDeno;
  84. this.reduce();
  85. return this;
  86. }
  87. public void printFraction(){
  88. System.out.println(this.numerator + "/" + this.denominator);
  89. }
  90.  
  91. /**
  92. * compare this with other, notice that param is Object type
  93. */
  94. public boolean equals(Object obj) {
  95. if (obj instanceof Fraction) {
  96. Fraction other = (Fraction) obj;
  97. this.reduce();
  98. other.reduce();
  99. if (this.numerator == other.numerator && this.denominator == other.denominator) return true;
  100. else return false;
  101. } else return false;
  102. }
  103.  
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement