Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Fraction {
- /**
- * declare attributes here
- */
- int numerator;
- int denominator;
- /**
- * declare constructor here
- */
- public Fraction(int numerator, int denominator){
- this.numerator = numerator;
- this.denominator = denominator;
- }
- /**
- * methods
- */
- private int gcd(int a, int b) {
- int temp;
- while (b!=0){
- temp = a % b;
- a = b;
- b = temp;
- }
- return a;
- }
- public int getNumerator(){
- return numerator;
- }
- public int getDenominator(){
- return denominator;
- }
- public void setNumerator(int number){
- numerator = number;
- }
- public void setDenominator(int number){
- denominator=number;
- }
- public Fraction reduce(){
- int n = gcd(numerator, denominator);
- numerator /=n;
- denominator /=n;
- return this;
- }
- // add
- public Fraction add(Fraction other) {
- int newNum = (this.numerator*other.denominator + this.denominator*other.numerator);
- int newDeno= this.denominator*other.denominator;
- this.numerator = newNum;
- this.denominator=newDeno;
- this.reduce();
- return this;
- }
- //subtract
- public Fraction subtract(Fraction other) {
- int newNum = (this.numerator*other.denominator - this.denominator*other.numerator);
- int newDeno= this.denominator*other.denominator;
- this.numerator = newNum;
- this.denominator=newDeno;
- this.reduce();
- return this;
- }
- // multiple
- public Fraction multiply(Fraction other) {
- int newNum = (this.numerator*other.numerator);
- int newDeno= this.denominator*other.denominator;
- this.numerator = newNum;
- this.denominator=newDeno;
- this.reduce();
- return this;
- }
- // divide
- public Fraction divide(Fraction other) {
- int newNum = (this.numerator*other.denominator);
- int newDeno= this.denominator*other.numerator;
- this.numerator = newNum;
- this.denominator=newDeno;
- this.reduce();
- return this;
- }
- public void printFraction(){
- System.out.println(this.numerator + "/" + this.denominator);
- }
- /**
- * compare this with other, notice that param is Object type
- */
- 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement