Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a java class called Fraction, for storing and manipulating fractions with

ID: 640938 • Letter: W

Question

Write a java class called Fraction, for storing and manipulating fractions with integer numerators and denominators. Fractions need to have two fields; one for the numerator and one for the denominator. Your fraction class also needs to have two methods: one called .toString() for creating a string representation of the fraction, and one called .times() for multiplying one fraction by another. Lastly, you need to have two different constructors, one which takes two integers (a numerator and a denominator) to define a new fraction, and one whic just takes a single integer (assuming that the denominators is 1). Don't worry about converting things to lowest terms for now.

Explanation / Answer


public class Fraction {
   private int numerator;
   private int denominator;
   Fraction(int num, int denum){
       numerator = num;
       denominator = denum;
   }
   Fraction(int num){
       numerator = num;
       denominator = 1;
   }
   public String toString(){
       return String.format("%d/%d", numerator, denominator);
   }
   public Fraction times(Fraction f){
       int num = numerator * f.numerator;
       int denum = denominator * f.denominator;
       return new Fraction(num, denum);
   }
   public static void main(String args[]){
       Fraction f1 = new Fraction(2, 3);
       Fraction f2 = new Fraction(2);
       System.out.println("f1 is: " + f1);
       System.out.println("f2 is: " + f2);
       Fraction f3 = f1.times(f2);
       System.out.println("f3 = f1 * f2");
       System.out.println("f3 is: " + f3);
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote