Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Term 2 Assignment 1 - Fraction */
- /* A class which is used to represent fractions */
- public class Fraction {
- private int numerator;
- private int denominator;
- private static final int NUMERATOR_VAL = 1;
- private static final int DENOMINATOR_VAL = 1;
- // default constructor which creates a fraction 1/1
- public Fraction() {
- this.numerator = NUMERATOR_VAL;
- this.denominator = DENOMINATOR_VAL;
- }
- // If n is positive, set numerator to n. Otherwise, set numerator to 1.
- // If d is positive, set denominator to d. Otherwise, set denominator to 1.
- public Fraction(int n, int d) {
- this.numerator = (n < 0) ? NUMERATOR_VAL : n;
- this.denominator = (d < 0) ? DENOMINATOR_VAL : d;
- // OR USE BELOW!
- /*
- if (n < 0) {
- this.numerator = NUMERATOR_VAL;
- } else {
- this.numerator = n;
- }
- if (d < 0) {
- this.denominator = DENOMINATOR_VAL;
- } else {
- this.denominator = d;
- }
- */
- }
- // Returns the fraction as a string in the format “numerator/denominator”
- public String toString() {
- return numerator + "/" + denominator;
- }
- // Returns any improper (top-heavy) fraction as a mixed number, for example, 2 3/5.
- // If the numerator of the fraction part is 0, return only the integer part of the mixed number.
- // If the fraction is proper, return only the fraction part.
- public String mixedNumber() {
- int whole = (this.numerator / this.denominator);
- int mixedNumerator = (numerator % denominator);
- if (mixedNumerator == 0) {
- return String.valueOf(whole);
- } else if (this.numerator < this.denominator) {
- return this.numerator + "/" + this.denominator;
- } else {
- return whole + " " + mixedNumerator + "/" + this.denominator;
- }
- }
- // If n and d are both positive, add the fraction n/d to this fraction.
- // Otherwise, leave the fractions unchanged.
- // In general the sum of the fractions a/b and c/d is(a*d + c*b)/(b*d).
- public Fraction add(int n, int d) {
- Fraction sum = this;
- if (n > 0 && d > 0) {
- int newNumerator = ((this.numerator * d) + (n * this.denominator));
- int newDenominator = (this.denominator * d);
- sum = new Fraction(newNumerator, newDenominator);
- }
- return sum;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment