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

Define a class called Fraction. This class is used to calculate the ratio of two

ID: 3730957 • Letter: D

Question

Define a class called Fraction. This class is used to calculate the ratio of two integers. . The class should have integer variables for the numerator and denominator The class should have a method that allows you to set a value for the numerator. The class should have a method that allows you to set a value for the denominator. The class should have a method that divides the numerator by the denominator and returns the result value as a double. Write a test program that creates an instance of the Fraction class and calculates the following ratios 1/3 2/3 75/100

Explanation / Answer

Fraction class code in java:

public class Fraction

{

//instance integer variables

int numerator,denominator;

//method to set value for the numerator

public void setNumerator(int numerator)

{

this.numerator = numerator;

}

//method to set value for the denominator

public void setDenominator(int denominator)

{

this.denominator = denominator;

}

//method to divide the numerator by denominator

public double divide()

{

/*converting integer value to double of both numerator and denominator

to get the desired output*/

return ((double)numerator/(double)denominator);

}

public static void main(String[] args)

{

//1st instance of Fraction class

Fraction ob1= new Fraction();

//setting values for both numerator and denominator

ob1.setNumerator(1);

ob1.setDenominator(3);

System.out.println("Result of divide= "+ob1.divide());

//2nd instance of Fraction class

Fraction ob2= new Fraction();

ob2.setNumerator(2);

ob2.setDenominator(3);

System.out.println("Result of divide= "+ob2.divide());

//3rd instance of Fraction class

Fraction ob3= new Fraction();

ob3.setNumerator(75);

ob3.setDenominator(100);

System.out.println("Result of divide= "+ob3.divide());

}

}

Output:

Result of divide= 0.3333333333333333
Result of divide= 0.6666666666666666
Result of divide= 0.75

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