Advertisement
16112

Fraction object

Mar 17th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class program {
  4.  
  5.     public static void main(String[] args) {
  6.         Scanner sc = new Scanner(System.in);
  7.  
  8.         int n = Integer.parseInt(sc.nextLine());
  9.         int d = Integer.parseInt(sc.nextLine());
  10.  
  11.         fraction drob = new fraction(n, d);
  12.         System.out.println("Drob1 = " + drob);
  13.  
  14.         fraction drob2 = new fraction(7, 5);
  15.         System.out.println("Drob2 = " + drob2);
  16.  
  17.         fraction drob3 = drob.multiply(drob2);
  18.         System.out.println("Drob3 = " + drob3);
  19.  
  20.         fraction drob4 = drob.sum(drob3);
  21.         System.out.println("Drob4 = " + drob4);
  22.  
  23.         fraction drob5 = drob.substract(drob4);
  24.         System.out.println("Drob5 = " + drob5);
  25.     }
  26.  
  27. }
  28.  
  29. ----------------------------------------------------
  30.  
  31. public class fraction {
  32.     private int numerator;
  33.     private int denominator;
  34.  
  35.     public fraction(int n, int d) {
  36.         this.numerator = n;
  37.         this.denominator = d;
  38.     }
  39.  
  40.     public String toString() {
  41.         String str = this.numerator + "/" + this.denominator;
  42.         return str;
  43.     }
  44.  
  45.     public fraction multiply(fraction other) {
  46.         int n = this.numerator * other.numerator;
  47.         int d = this.denominator * other.denominator;
  48.         fraction fr = new fraction(n, d);
  49.         return fr;
  50.     }
  51.  
  52.     public fraction sum(fraction other) {
  53.         int n = this.numerator * other.denominator + other.numerator * this.denominator;
  54.         int d = this.denominator + other.denominator;
  55.         fraction fr = new fraction(n, d);
  56.         return fr;
  57.     }
  58.  
  59.     public fraction substract(fraction other) {
  60.         int n = this.numerator * other.denominator - other.numerator * this.denominator;
  61.         int d = this.denominator + other.denominator;
  62.         fraction fr = new fraction(n, d);
  63.         return fr;
  64.     }
  65.  
  66.     public int gcd(int a, int b) {
  67.         for (int i = Math.min(a, b); i >= 1; i--) {
  68.             if (a % 1 == 0 && b % 1 == 0) {
  69.                 return i;
  70.             }
  71.         }
  72.         return 1;
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement