I have a question in class that is due tomorrow. I need help trying to figure ou
ID: 3542982 • Letter: I
Question
I have a question in class that is due tomorrow. I need help trying to figure out where I'm going wrong and completeing it.
Question:
Define a class called Fraction. This class is used to represent a ratio of two integers. Include mutotor methods that allow the user to set the numberator and the denominator. Also include a method that returns the value of numerator divided by denominator as a double. Include an additional method that outputs the value of the fraction reduced to lowest terms (e.g, instead of outputting 20/60, the method should output 1/3). This will require finding the greatest common divisor for the numerator and denominator, then dividing both by that number. Embed your class in a test program.
This is what I have so far....
package fraction;
public class Fraction {
private int numerator;
private int denominator;
//blank constructor
public void Fraction()
{
numerator = 0;
denominator = 1;
}
// constructor method
public void Fraction(int n, int d)
{
numerator = n;
denominator = d;
{
//mutator method
public void setNumerator(int n)
{
numerator = n;
}
public void setDenominator(int d)
{
denominator = d;
}
public void displayAsRatio()
{
System.out.println(numerator + ":" + denominator); //ratio uses a colon
}
}
}
}
Explanation / Answer
It answers properly your question and also TEST PROGRAM FOR USER included
From program i can see you are running NetBeans , so this is the exact program you want and it works properly you can just copy and run it
Please rate - thanks
doubts - post
package fraction;
import java.util.Scanner;
public class Fraction {
private int numerator;
private int denominator;
//blank constructor
public void Fraction()
{
numerator = 0;
denominator = 1;
}
//mutator methods
public void setNumerator(int n)
{
numerator = n;
}
public void setDenominator(int d)
{
denominator = d;
}
//method displaying result in double format
public double displayAsRatio()
{
return numerator/(double)denominator;
}
//method displaying result in reduced fraction format
public void fractionReduced(){
System.out.println(numerator/findGCD(numerator, denominator) + "/" + denominator/findGCD(numerator, denominator));
}
private static int findGCD(int number1, int number2) {
//base case
if(number2 == 0){
return number1;
}
return findGCD(number2, number1%number2);
}
//TEST PROGRAM FOR USER
public static void main(String args[]){
Fraction f=new Fraction();
Scanner in=new Scanner(System.in);
System.out.println("enter numerator :");
f.setNumerator(in.nextInt());
System.out.println("enter denominator :");
f.setDenominator(in.nextInt());
f.fractionReduced();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.