Reputation: 15
This question is towards the last method. Whenever I return d in the method "public static Rational convert(double d)" it says that it can not convert from double to Rational. How would I make it so that I would be able to return a Rational number from the method without switching "Rational" to double or the parameter? And is that how I would implement a loop to find the GCF in the method as well, without creating another method?
public class Rational
{
// The state of a rational number is just the numerator and denominator.
private static int numerator;
private static int denominator;
// When created, a Rational's numerator and denominator are set.
public Rational( int num, int den )
{
numerator = num;
denominator = den;
}
// Accessor method for the numerator
public int getNumerator( )
{
return numerator;
}
// Accessor method for the denominator
public int getDenominator( )
{
return denominator;
}
// A mutator method which doubles the given rational number by doubling the
// numerator.
public void doubleNumber( )
{
numerator *= 2;
}
// A method which returns the common denominator between the current and
// given rational. Specifically, returns the denominator multiplied by the
// denominator of the given rational number.
public int findCommonDenominator( Rational r )
{
return denominator * r.getDenominator( );
}
//Method returning the decimal value of the fraction.
public static double convert(Rational r)
{
return (double) numerator / (double) denominator;
}
//Method returning the smallest fraction possible from a decimal given.
public static Rational convert(double d)
{
d = (Math.floor(d * 100)/100);
while ( denominator != 0)
{
d = (double) (numerator % denominator);
numerator = denominator;
d = (double) (denominator);
}
return d;
}
Upvotes: 1
Views: 1181
Reputation: 1877
Your while loop will probably never end. You never change the value of denominator.
Now, for the method public static Rational convert(double d)
You're returning a double, how does Java know that you want d to be a Rational?
It doesn't.
In that method you should be doing a return closer to:
Rational converted = new Rational(numerator, denominator);
return converted;
But before you do that you have to initialize both in the method.
You have a lot of work to do here.
double d
to the method, then don't use the value, just overwrite it.while(denominator != 0)
because you never change denominators value.Rational rational = Rational.convert(someDouble);
So you should consider declaring a numerator and denominator inside of the method, and returning something like new Rational(num,dem);
Upvotes: 1