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/100Explanation / 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
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.