Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. public class Fraction {
  2. private int numerator, denominator=1;
  3.  
  4. public int getNumerator(){
  5. return numerator;
  6. }
  7. public int getDenominator(){
  8. return denominator;
  9. }
  10. public void setNumerator(int numerator){
  11. this.numerator = numerator;
  12. }
  13. public void setDenominator(int denominator){
  14. if (denominator!=0) this.denominator = denominator;
  15. }
  16. public Fraction(int numerator, int denominator){
  17. if (denominator==0) return;
  18. this.numerator = numerator;
  19. this.denominator = denominator;
  20. }
  21.  
  22. public static int gcd(int a, int b) {
  23. while (b!=0){
  24. int temp = a % b;
  25. a = b;
  26. b = temp;
  27. }
  28. return a;
  29. }
  30.  
  31. public Fraction reduce(){
  32. int n = gcd(numerator, denominator);
  33. this.numerator /=n;
  34. this.denominator /=n;
  35. return this;
  36.  
  37. }
  38.  
  39. public Fraction add(Fraction other) {
  40. this.numerator = this.numerator*other.denominator + other.numerator*this.denominator;
  41. this.denominator = this.denominator*other.denominator;
  42. return this;
  43. }
  44. public Fraction subtract(Fraction other) {
  45. this.numerator = this.numerator*other.denominator - other.numerator*this.denominator;
  46. this.denominator = this.denominator*other.denominator;
  47. return this;
  48. }
  49.  
  50. public Fraction multiply(Fraction other) {
  51. this.numerator = this.numerator*other.numerator;
  52. this.denominator = this.denominator*other.denominator;
  53. return this;
  54. }
  55.  
  56. public Fraction divide(Fraction other) {
  57. if(other.numerator==0) return this;
  58. this.numerator = this.numerator*other.denominator;
  59. this.denominator = this.denominator*other.numerator;
  60. return this;
  61. }
  62.  
  63. public boolean equals(Object obj) {
  64. if (obj instanceof Fraction) {
  65. Fraction other = (Fraction) obj;
  66. this.reduce();
  67. other.reduce();
  68. if (this.numerator==other.numerator&&this.denominator==other.denominator) return true;
  69. else return false;
  70. } else return false;
  71. }
  72. // public static void main(String agrs[]){
  73. // Scanner newScan= new Scanner(System.in);
  74. // Fraction new1 = new Fraction(1,1);
  75. // Fraction new2 = new Fraction(2,0);
  76. // System.out.println(new1.equals(new2));
  77. // new1.subtract(new2);
  78. // new1.printFraction();
  79. // }
  80.  
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement