Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Fraction {
- private int numerator, denominator=1;
- public int getNumerator(){
- return numerator;
- }
- public int getDenominator(){
- return denominator;
- }
- public void setNumerator(int numerator){
- this.numerator = numerator;
- }
- public void setDenominator(int denominator){
- if (denominator!=0) this.denominator = denominator;
- }
- public Fraction(int numerator, int denominator){
- if (denominator==0) return;
- this.numerator = numerator;
- this.denominator = denominator;
- }
- public static int gcd(int a, int b) {
- while (b!=0){
- int temp = a % b;
- a = b;
- b = temp;
- }
- return a;
- }
- public Fraction reduce(){
- int n = gcd(numerator, denominator);
- this.numerator /=n;
- this.denominator /=n;
- return this;
- }
- public Fraction add(Fraction other) {
- this.numerator = this.numerator*other.denominator + other.numerator*this.denominator;
- this.denominator = this.denominator*other.denominator;
- return this;
- }
- public Fraction subtract(Fraction other) {
- this.numerator = this.numerator*other.denominator - other.numerator*this.denominator;
- this.denominator = this.denominator*other.denominator;
- return this;
- }
- public Fraction multiply(Fraction other) {
- this.numerator = this.numerator*other.numerator;
- this.denominator = this.denominator*other.denominator;
- return this;
- }
- public Fraction divide(Fraction other) {
- if(other.numerator==0) return this;
- this.numerator = this.numerator*other.denominator;
- this.denominator = this.denominator*other.numerator;
- return this;
- }
- public boolean equals(Object obj) {
- if (obj instanceof Fraction) {
- Fraction other = (Fraction) obj;
- this.reduce();
- other.reduce();
- if (this.numerator==other.numerator&&this.denominator==other.denominator) return true;
- else return false;
- } else return false;
- }
- // public static void main(String agrs[]){
- // Scanner newScan= new Scanner(System.in);
- // Fraction new1 = new Fraction(1,1);
- // Fraction new2 = new Fraction(2,0);
- // System.out.println(new1.equals(new2));
- // new1.subtract(new2);
- // new1.printFraction();
- // }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement