The document defines a Fraction class with private fields for the numerator and denominator. It includes constructors to initialize fractions with default or specified values. Methods are provided to get/set the numerator and denominator, add and multiply fractions, convert to string representations, and track the total number of fractions created.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
22 views2 pages
Solved by Verified Expert: Rated Helpful
The document defines a Fraction class with private fields for the numerator and denominator. It includes constructors to initialize fractions with default or specified values. Methods are provided to get/set the numerator and denominator, add and multiply fractions, convert to string representations, and track the total number of fractions created.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2
Answer & Explanation
Solved by verified expert
Rated Helpful class Fraction { private int numerator; private int denominator; private static int numFractions = 0; public Fraction(){ numerator = 1; denominator = 1; numFractions++; } public Fraction(int n, int d){ if(n>0){ numerator = n; } else{ n=1; } if(d>0){ denominator = d; } else{ d= 1; } numFractions++; } public int getNumerator(){ return numerator; } public int getDenominator(){ return denominator; } static int getNumFractions(){ return numFractions; } public String toString(){ return String.format("%d/%d",numerator,denominator); } public String mixedNumber(){ if(numerator < denominator){ return toString(); } if(numerator%denominator == 0){ return String.format("%d",numerator/denominator); } return String.format("%d %d/%d",numerator/denominator, numerator%denominator, denominator); } public void setNumerator(int n){ if(n>0){ numerator = n; } } void setDenominator(int d){ if(d>0){ denominator = d; } } void add(int n, int d){ if(n>0 && d>0){ int currNumerator = numerator; int currDenominator = denominator; numerator = (currNumerator*d) + (n*currDenominator); denominator = (currDenominator*d); } } void add(Fraction other){ int currNumerator = numerator; int currDenominator = denominator; numerator = (currNumerator*other.getDenominator()) + (other.getNumerator()*currDenominator); denominator = (currDenominator*other.getDenominator()); } void multiply(int n, int d){ if(n>0 && d>0){ numerator = numerator * n; denominator = denominator *d; } } void multiply(Fraction other){ numerator = numerator * other.getNumerator(); denominator = denominator * other.getDenominator(); } } Step-by-step explanation I have written the code. Can you please test this code with the inputs that are given. If you face any issue, please let me know in comments. I will assist you fully. Have a nice day! Thank you!