Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Interface implementation? 1

Status
Not open for further replies.

jisoo22

Programmer
Apr 30, 2001
277
US
Hello all,

I'm taking classes for Java and doing pretty well for a newbie with no previous software programming experience (making html webpages just don't count hehe). I'm having a little trouble with one of my assignments that looks pretty simple. I know the concept and what must be accomplished but I'm not quite sure how to go about it. Here's what I need to do...

I have a driver program and a class program. The gist of it is that I need to create a method that compares two objects (each containing a rational number) and if they are close enough together, will output 0 because they are considered even (to within 0.0001 of each other). Correspondingly, if they are more then 0.0001 apart it outputs -1 and 1 respectively. My problem is that I'm not sure how to compare two class objects within my method. I know how to compare variables and string objects, but not such large objects like class instantiations. The method I created is called "compareTo" and has obvious problems (though the logic may be correct?). I have posted both the class and driver programs below. Before I forget, the class program implements the "Comparable" interface. Here's a link to it's API definition
Don't worry about the other methods in the class program, they all seem to work =) Any ideas would be appreciated!

Thanks,
Jisoo22

class program

public class Rational implements Comparable
{
private int numerator, denominator;
private double tolerance = 0.0001;

//-----------------------------------------------------------------
// Sets up the rational number by ensuring a nonzero denominator
// and making only the numerator signed.
//-----------------------------------------------------------------
public Rational (int numer, int denom)
{
if (denom == 0)
denom = 1;

// Make the numerator "store" the sign
if (denom < 0)
{
numer = numer * -1;
denom = denom * -1;
}

numerator = numer;
denominator = denom;

reduce();
}

//-----------------------------------------------------------------
// Compares two rational numbers and if they are within tolerance
// are considered even (or 0). If not, then -1 or 1 is outputted
// to show that the first rational number is less than or greater
// than the second. Currently a work in progress.
//-----------------------------------------------------------------

public Rational compareTo ( Rational ob1, Rational ob2 )
{
int obValue = 0;
double compared = ob1 - ob2;

if (compared <= tolerance)
{
return obValue;
}
else if ( compared > tolerance )
{
obValue = obValue + 1;
return obValue;
}
else
{
obValue = obValue - 1;
return obValue;
}
}

//-----------------------------------------------------------------
// Adds this rational number to the one passed as a parameter.
// A common denominator is found by multiplying the individual
// denominators.
//-----------------------------------------------------------------
public Rational add (Rational op2)
{
int commonDenominator = denominator * op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int sum = numerator1 + numerator2;

return new Rational (sum, commonDenominator);
}

//-----------------------------------------------------------------
// Subtracts the rational number passed as a parameter from this
// rational number.
//-----------------------------------------------------------------
public Rational subtract (Rational op2)
{
int commonDenominator = denominator * op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int difference = numerator1 - numerator2;

return new Rational (difference, commonDenominator);
}

//-----------------------------------------------------------------
// Multiplies this rational number by the one passed as a
// parameter.
//-----------------------------------------------------------------
public Rational multiply (Rational op2)
{
int numer = numerator * op2.getNumerator();
int denom = denominator * op2.getDenominator();

return new Rational (numer, denom);
}

//-----------------------------------------------------------------
// Divides this rational number by the one passed as a parameter
// by multiplying by the reciprocal of the second rational.
//-----------------------------------------------------------------
public Rational divide (Rational op2)
{
return multiply (op2.reciprocal());
}

//-----------------------------------------------------------------
// Returns the reciprocal of this rational number.
//-----------------------------------------------------------------
public Rational reciprocal ()
{
return new Rational (denominator, numerator);
}

//-----------------------------------------------------------------
// Returns the numerator of this rational number.
//-----------------------------------------------------------------
public int getNumerator ()
{
return numerator;
}

//-----------------------------------------------------------------
// Returns the denominator of this rational number.
//-----------------------------------------------------------------
public int getDenominator ()
{
return denominator;
}

//-----------------------------------------------------------------
// Determines if this rational number is equal to the one passed
// as a parameter. Assumes they are both reduced.
//-----------------------------------------------------------------
public boolean equals (Rational op2)
{
return ( numerator == op2.getNumerator() &&
denominator == op2.getDenominator() );
}

//-----------------------------------------------------------------
// Returns this rational number as a string.
//-----------------------------------------------------------------
public String toString ()
{
String result;

if (numerator == 0)
result = &quot;0&quot;;
else
if (denominator == 1)
result = numerator + &quot;&quot;;
else
result = numerator + &quot;/&quot; + denominator;

return result;
}

//-----------------------------------------------------------------
// Reduces this rational number by dividing both the numerator
// and the denominator by their greatest common divisor.
//-----------------------------------------------------------------
private void reduce ()
{
if (numerator != 0)
{
int common = gcd (Math.abs(numerator), denominator);

numerator = numerator / common;
denominator = denominator / common;
}
}

//-----------------------------------------------------------------
// Computes and returns the greatest common divisor of the two
// positive parameters. Uses Euclid's algorithm.
//-----------------------------------------------------------------
private int gcd (int num1, int num2)
{
while (num1 != num2)
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;

return num1;
}
}



driver program

public class RationalNumbers
{
//-----------------------------------------------------------------
// Creates some rational number objects and performs various
// operations on them.
//-----------------------------------------------------------------
public static void main( String [] args ){
Rational r1 = new Rational( 1, 10000 ); // .0001
Rational r2 = new Rational( 1, 10000 ); // .0001
Rational r3 = new Rational( 2, 10000 ); // .0002
Rational r4 = new Rational( 3, 10000 ); // .0003

System.out.println( &quot;should be 0:&quot; + r1.compareTo( r2 ) );
System.out.println( &quot;should be 0:&quot; + r1.compareTo( r3 ) ); //in tolerance
System.out.println( &quot;should be 0:&quot; + r1.compareTo( r1 ) );
System.out.println( &quot;should be -1:&quot; + r1.compareTo( r4 ) );
System.out.println( &quot;should be 1:&quot; + r4.compareTo( r1 ) );
} //main

}
 
Try turning off tgml or puttong the whole chunk of code in code tags so the i indexes won't make it italics :) --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
For my next trick I will pull a hat out of a rabbit (if you think thats bad you should see how the pigeon feels...) :p
 
Thanks for the tip, though this doesn't seem to relate to my previous question?
 
Hi jisoo32,
It's related to your posting. Code posted in threads needs to be surrounded by [ignore]
Code:
[/ignore] or [ignore][tt][/tt][/ignore] to prevent the common usage of arrays and the code [ignore][/ignore] from matching the italics tgml tag, which causes the code to appear in italics and difficult to read. Most people won't look at it if it's like this, so repost with [ignore]
Code:
[/ignore] or [ignore][tt][/tt][/ignore] surrounding your code section.

MarsChelios
 
Ok, here's the reposted code in a better format. Any help is greatly appreciated!

P.S. The compareTo method has been adjusted because I realized that it returns an int (but I need to work with doubles within it to find out whether two Rationals are even or not).

class program
Code:
public class Rational implements Comparable
{
    private int numerator, denominator;
    private double tolerance = 0.0001;
    //-----------------------------------------------------------------
    //  Sets up the rational number by ensuring a nonzero denominator
    //  and making only the numerator signed.
    //-----------------------------------------------------------------
    public Rational (int numer, int denom)
    {
        if (denom == 0)
            denom = 1;
        // Make the numerator &quot;store&quot; the sign
        if (denom < 0)
        {
            numer = numer * -1;
            denom = denom * -1;
        }
        numerator = numer;
        denominator = denom;
        reduce();
    }
    //-----------------------------------------------------------------
    //  Compares two rational numbers and if they are within tolerance
    //  are considered even (or 0).  If not, then -1 or 1 is outputted
    //  to show that the first rational number is less than or greater
    //  than the second.  Currently a work in progress.
    //-----------------------------------------------------------------
    public int compareTo ( Object ob1 )
    {
        Rational ratobj = (Rational) ob1;
        int obValue = 0;
        double compared = rateobj - this;
        if (compared <= tolerance)
        {
            return obValue;
        }
        else if ( compared > tolerance )
        {
            obValue = obValue + 1;
            return obValue;
        }
        else
        {
            obValue = obValue - 1;
            return obValue;
        }
    }
    //-----------------------------------------------------------------
    //  Adds this rational number to the one passed as a parameter.
    //  A common denominator is found by multiplying the individual
    //  denominators.
    //-----------------------------------------------------------------
    public Rational add (Rational op2)
    {
        int commonDenominator = denominator * op2.getDenominator();
        int numerator1 = numerator * op2.getDenominator();
        int numerator2 = op2.getNumerator() * denominator;
        int sum = numerator1 + numerator2;
        return new Rational (sum, commonDenominator);
    }
    //-----------------------------------------------------------------
    //  Subtracts the rational number passed as a parameter from this
    //  rational number.
    //-----------------------------------------------------------------
    public Rational subtract (Rational op2)
    {
        int commonDenominator = denominator * op2.getDenominator();
        int numerator1 = numerator * op2.getDenominator();
        int numerator2 = op2.getNumerator() * denominator;
        int difference = numerator1 - numerator2;
        return new Rational (difference, commonDenominator);
    }
    //-----------------------------------------------------------------
    //  Multiplies this rational number by the one passed as a
    //  parameter.
    //-----------------------------------------------------------------
    public Rational multiply (Rational op2)
    {
        int numer = numerator * op2.getNumerator();
        int denom = denominator * op2.getDenominator();
        return new Rational (numer, denom);
    }
    //-----------------------------------------------------------------
    //  Divides this rational number by the one passed as a parameter
    //  by multiplying by the reciprocal of the second rational.
    //-----------------------------------------------------------------
    public Rational divide (Rational op2)
    {
        return multiply (op2.reciprocal());
    }
    //-----------------------------------------------------------------
    //  Returns the reciprocal of this rational number.
    //-----------------------------------------------------------------
    public Rational reciprocal ()
    {
        return new Rational (denominator, numerator);
    }
    //-----------------------------------------------------------------
    //  Returns the numerator of this rational number.
    //-----------------------------------------------------------------
    public int getNumerator ()
    {
        return numerator;
    }
    //-----------------------------------------------------------------
    //  Returns the denominator of this rational number.
    //-----------------------------------------------------------------
    public int getDenominator ()
    {
        return denominator;
    }
    //-----------------------------------------------------------------
    //  Determines if this rational number is equal to the one passed
    //  as a parameter.  Assumes they are both reduced.
    //-----------------------------------------------------------------
    public boolean equals (Rational op2)
    {
        return ( numerator == op2.getNumerator() &&
                    denominator == op2.getDenominator() );
    }
    //-----------------------------------------------------------------
    //  Returns this rational number as a string.
    //-----------------------------------------------------------------
    public String toString ()
    {
        String result;
        if (numerator == 0)
            result = &quot;0&quot;;
        else
            if (denominator == 1)
                result = numerator + &quot;&quot;;
            else
                result = numerator + &quot;/&quot; + denominator;
        return result;
    }
    //-----------------------------------------------------------------
    //  Reduces this rational number by dividing both the numerator
    //  and the denominator by their greatest common divisor.
    //-----------------------------------------------------------------
    private void reduce ()
    {
        if (numerator != 0)
        {
            int common = gcd (Math.abs(numerator), denominator);
            numerator = numerator / common;
            denominator = denominator / common;
        }
    }
    //-----------------------------------------------------------------
    //  Computes and returns the greatest common divisor of the two
    //  positive parameters. Uses Euclid's algorithm.
    //-----------------------------------------------------------------
    private int gcd (int num1, int num2)
    {
        while (num1 != num2)
            if (num1 > num2)
                num1 = num1 - num2;
            else
                num2 = num2 - num1;
        return num1;
    }
}

driver program
Code:
public class RationalNumbers
{
    //-----------------------------------------------------------------
    //  Creates some rational number objects and performs various
    //  operations on them.
    //-----------------------------------------------------------------
    public static void main( String [] args ){
        Rational r1 = new Rational( 1, 10000 ); // .0001
        Rational r2 = new Rational( 1, 10000 ); // .0001
        Rational r3 = new Rational( 2, 10000 ); // .0002
        Rational r4 = new Rational( 3, 10000 ); // .0003
        System.out.println( &quot;should be 0:&quot; + r1.compareTo( r2 ) );
        System.out.println( &quot;should be 0:&quot; + r1.compareTo( r3 ) ); //in tolerance
        System.out.println( &quot;should be 0:&quot; + r1.compareTo( r1 ) );
        System.out.println( &quot;should be -1:&quot; + r1.compareTo( r4 ) );
        System.out.println( &quot;should be 1:&quot; + r4.compareTo( r1 ) );
    } //main
}

 
Hmm, well retObj appears to be spelled wrong for one, try this:
double compared = ratobj.subtract(this);

That might help out a little, otherwise it won't understand what you want it to do with the subtraction :)

Now we have a function returning a Rational object into a double, won't work. Since the Rational being returned has already been reduced, we don't actually know what the gcd was it reduced by so we can't go backwards. We can however simply divide the numerator by the denominator:

Rational diff = this.subtract(ratobj);
double compared = diff.getNumerator() / diff.getDenominator();


But then we get a whole lot of 0.0's because doubles don't hold decvimals as well as they should. SO we convert the declaration of tolerance to be a float like so:

private float tolerance = (float)0.0001;

Then make the following changes to fill it:

Rational ratobj = (Rational) ob1;
int obValue = 0;
Rational diff = this.subtract(ratobj);
float compared = (float)diff.getNumerator() / (float)diff.getDenominator();

All well and good, it works for positive numbers now, but our comparison between compared and tolerance will not work so well for negatice number because a negative number is always less than a positive tolerance, so we need to compare the absolute value of the differance (compared variable)

if (Math.abs(compared) <= tolerance)

And tada! we have a compareTo function :)

Hope this helps,
-Tarwn
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
For my next trick I will pull a hat out of a rabbit (if you think thats bad you should see how the pigeon feels...) :p
 
Sorry, didn't spell check, that misspell above (first line) should have been:
...rateObj seems to be spelled wrong for one, try this:
double compared = ratobj.subtract(this);

also paragraph 5ish, decimal doesn't have a v in it :p
obviously it must go in the &quot;negatice&quot; later on that should have been negative

Sorry, I'll spell check next time :)
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
For my next trick I will pull a hat out of a rabbit (if you think thats bad you should see how the pigeon feels...) :p
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top