Results 1 to 17 of 17
  1. #1
    RachLee is offline Member
    Join Date
    Oct 2014
    Posts
    6
    Rep Power
    0

    Default Fraction Class equals method issue

    Hi, I am working on a program and everything is going fine except for the equals method. It keeps outputting "frac1 and frac2 NOT equal." What am I doing wrong in the code?

    Test Driver:
    Java Code:
    public class FractionClassTestDriver {
        public static void main(String[] args) {
            
            	// test constructors
            	Fraction frac0 = new Fraction();
            	System.out.println("TESTING NO-ARG CONSTRUCTOR");
    		System.out.println("frac0: Result should be 0/1:");
            	System.out.println("Numer = " + frac0.getNumer());
            	System.out.println("Denom = " + frac0.getDenom());
            
            	System.out.println("TESTING int/int CONSTRUCTOR");
            	Fraction frac1 = new Fraction(2,4);
    		System.out.println("frac1: Result should be 2/4:");
            	System.out.println("Numer = " + frac1.getNumer());
            	System.out.println("Denom = " + frac1.getDenom());
            
            	System.out.println("TESTING Fraction CONSTRUCTOR");
            	Fraction frac2 = new Fraction(frac1);
    		System.out.println("frac2: Result should be 2/4:");
            	System.out.println("Numer = " + frac2.getNumer());
            	System.out.println("Denom = " + frac2.getDenom());
    
    
    		System.out.println("TESTING COPY CONSTRUCTOR frac1 → frac2");
            	if (frac1.getNumer() == frac2.getNumer() &&
                		frac1.getDenom() == frac2.getDenom() &&
                  		frac1 != frac2)
            	{
                		System.out.println("Copy constructor working");
            	}
            	else
                		System.out.println("PROBLEM with copy constructor");
    
            
            	// test equal method
            	System.out.println("TESTING EQUALITY OF frac1 and frac2 -");
    		System.out.println("SHOULD BE FOUND EQUAL:");
    		if (frac1.equals(frac2))
            	{
                		System.out.println("frac1 and frac2 found equal");
            	}
            	else
            	{
                        
                		System.out.println("frac1 and frac2 NOT equal");
            	}
    
                	// test reduce method
            	System.out.println("TESTING reduce METHOD ON frac1");
    		Fraction reduced_frac1 = frac1.reduce();
            	System.out.println("Reduced frac1 = " + reduced_frac1);
            
            	// test getters and setters
            	frac2.setNumer(8);
            	frac2.setDenom(12);
            	System.out.println("Numer = " + frac2.getNumer());
            	System.out.println("Denom = " + frac2.getDenom());  
                    System.out.println("GCD of 2/4 = " + frac1.gcd(2,4));
                    System.out.println("TESTING addition 2/4+8/12");
                    System.out.println(frac1.add(frac2));
                    System.out.println("TESTING subtraction 2/4-8/12");
                    System.out.println(frac1.subtract(frac2));
                    System.out.println("TESTING multiplication 2/4*8/12");
                    System.out.println(frac1.multiply(frac2));
            
            	// System.out.println("GCD of 2/4 = " + frac1.gcd(1,4));
           
        	}
    
        
    }
    Fraction Class:

    Java Code:
    public class Fraction {
        private int numer;
        private int denom;
        
        	public Fraction() { // no-arg constructor
           		numer = 0;
            	denom = 1;
    	}
        
        	public Fraction(int numer, int denom) {
            	this.numer = numer;
            	this.denom = denom;
        	}
        
        	public Fraction(Fraction frac) { // copy constructor
            	numer = frac.getNumer();
            	denom = frac.getDenom();
        	}
    
         	// getters and setters
        	public int getNumer() {
            	return numer;
        	}
        
        	public void setNumer(int x) {
            	numer = x;
                    reduce();
        	}
        
        	public int getDenom()  {
            	return denom;
        	}
        
        	public void setDenom(int x) 
            {
            	if (x==0) {
                        denom=1;
                        System.out.println("Denominator can't be zero.");
                    }
                    else {
                        denom = x;
                    }
                   reduce();
        	}
            
            public boolean equals(Fraction f2)
            {
            return (numer==f2.numer) && (denom==f2.denom);
            }
       
     	// Special Methods
        @Override
        	public String toString() {
            	return numer + "/" + denom;
        	}
            
            public boolean lessThan(Fraction f2)
            {
                return (numer/denom) < (f2.numer/f2.denom);
            }
            
            public boolean greaterThan(Fraction f2)
            {
                return (numer/denom) > (f2.numer/f2.denom);
            }
    
        	// Other Methods
        	public Fraction reduce() {
            	Fraction temp = new Fraction();
            
            	int GCD = gcd(numer, denom);
            
            	temp.setNumer(numer / GCD);
            	temp.setDenom(denom / GCD);
            
            	return  temp;
        	}
            
            public Fraction add (Fraction f2) 
            {
                Fraction temp = new Fraction();
                temp.numer = (numer*f2.denom)+(f2.numer*denom);
                temp.denom =(denom*f2.denom)+(f2.denom*numer);
                temp=temp.reduce();
                
                return temp;
            }
            
            public Fraction subtract (Fraction f2) 
            {
                Fraction temp = new Fraction();
                temp.numer = ((numer*f2.denom)-(denom*f2.numer));
                temp.denom=(denom*f2.denom);
                temp=temp.reduce(); 
                
                return temp;
            }
            
            public Fraction multiply(Fraction f2)
            {
                Fraction temp = new Fraction();
                temp.numer = (numer*f2.denom);
                temp.denom=(denom*f2.numer);
                temp=temp.reduce();
                
                return temp;
            }
     	
    	 // Private Methods
        	int gcd(int n1, int n2)
        	{
            	int M, N, R;
            
            	if (n1 < n2)
            	{
                		N = n1;
                		M = n2;
            	}
            	else
            	{
                		N = n2;
               	 	M = n1;
            	}
            
            	R = M % N;
            
            	while (R != 0)
            	{
                		M = N;
                		N = R;
                
                		R = M % N;
            	}
            
            	return N;
            
            }
     }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Fraction Class equals method issue

    It keeps outputting "frac1 and frac2 NOT equal." What am I doing wrong in the code?
    Are they equal?
    Try doing some debugging by having the code print out the values of the two objects so you can see what the computer thinks they are.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    RachLee is offline Member
    Join Date
    Oct 2014
    Posts
    6
    Rep Power
    0

    Default Re: Fraction Class equals method issue

    Yes I had it print out both values and both is 2/4.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Fraction Class equals method issue

    Please copy the print out and paste here.
    Where are the print statements? They should be inside of the equals() method and should print the values of all 4 variables that are compared so you can see exactly what the computer sees where it compares the values.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Fraction Class equals method issue

    Here is an unrelated observation:

    In your gcd method, notice that if N > M, then R will be equal to M when it enters the loop. So the first thing that happens is that M and N are effectively swapped! So you don't need the check for n1 > n2 at the beginning. This means that "sometimes" the loop gets an extra iteration. And that is probably offset by not having to do the comparison at all.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Fraction Class equals method issue

    I also believe your multiply method is actually dividing.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    RachLee is offline Member
    Join Date
    Oct 2014
    Posts
    6
    Rep Power
    0

    Default Re: Fraction Class equals method issue

    We are supposed to put all of the print statements in the main. It uses the equals method in the main.

    Java Code:
    TESTING NO-ARG CONSTRUCTOR
    frac0: Result should be 0/1:
    Numer = 0
    Denom = 1
    TESTING int/int CONSTRUCTOR
    frac1: Result should be 2/4:
    Numer = 2
    Denom = 4
    TESTING Fraction CONSTRUCTOR
    frac2: Result should be 2/4:
    Numer = 2
    Denom = 4
    TESTING COPY CONSTRUCTOR frac1 → frac2
    Copy constructor working
    TESTING EQUALITY OF frac1 and frac2 -
    SHOULD BE FOUND EQUAL:
    frac1 and frac2 NOT equal
    TESTING reduce METHOD ON frac1
    Reduced frac1 = 1/2
    Numer = 8
    Denom = 12
    GCD of 2/4 = 2
    TESTING addition 2/4+8/12
    7/6
    TESTING subtraction 2/4-8/12
    1/-6
    TESTING multiplication 2/4*8/12
    1/2

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Fraction Class equals method issue

    There should be debug output between these two lines that shows the values of the 4 variables:
    SHOULD BE FOUND EQUAL:
    >>>>>>>>>>Print here the values of the 4 variables<<<<<<<<
    frac1 and frac2 NOT equal
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Fraction Class equals method issue

    You are not running the posted code. I just ran it. The fractions are equal. And notice your reduce() method. You call setNumer in the reduce method which itself calls reduce. So your TEST REDUCE code goes into stack overflow, not even reaching the other tests.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  10. #10
    RachLee is offline Member
    Join Date
    Oct 2014
    Posts
    6
    Rep Power
    0

    Default Re: Fraction Class equals method issue

    Thank you so much! I inputted everything over and I have no idea why it wasn't running that code.

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Fraction Class equals method issue

    Quote Originally Posted by RachLee View Post
    Thank you so much! I inputted everything over and I have no idea why it wasn't running that code.
    You're welcome but your code still has problems. You need to rethink your some of your operation methods (+, - ,etc). Go thru them by hand with pencil and paper.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    kire9dk is offline Member
    Join Date
    Sep 2009
    Posts
    16
    Rep Power
    0

    Default Re: Fraction Class equals method issue

    Hello, I checked your code and I noticed that your equals method takes Fraction object as input argument.

    Java expects this method to take object from the class Object
    Java Code:
    equals(Object obj)

    Java Code:
    @Override 
    public boolean equals(Object obj) { 
    	// check is it the same instance
    	if (obj == this) { 
    		return true; 
    	} 
    
    	// check if it is null or from different class
    	// Note: you can use here instanceof operator also if you have inheritance
    	if (obj == null || obj.getClass() != this.getClass()) { 
    		return false; 
    	} 
    	
    	// cast to your class
    	Fraction f2 = (Fraction) obj;
    	// your equals logic
    	return (numer==f2.numer) && (denom==f2.denom);
    }
    Best Regards

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Fraction Class equals method issue

    You should 'normalize' a fraction when you create it, i.e. for a potential fraction n/d, store n/g and d/g where g == gcd(n,d); also normalize the sign of the fraction, e.g. a negative fraction has a negative value for d (per convention). So 2/4 is stored as 1/2 and -2/4 is stored as 1/-2 and -2/-4 is stored as 1/2 etc.

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  14. #14
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Fraction Class equals method issue

    This would also be easier to implement and maintain and less prone to problems if you made the Fraction class immutable. I'm not certain the advantage of being able to allow the user to change an existing fraction's components. If you want a different fraction, then just instantiate one.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  15. #15
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Fraction Class equals method issue

    Quote Originally Posted by jim829 View Post
    This would also be easier to implement and maintain and less prone to problems if you made the Fraction class immutable. I'm not certain the advantage of being able to allow the user to change an existing fraction's components. If you want a different fraction, then just instantiate one.
    It would be silly to make them mutable; for one thing: it can screw up their 'natural' order; if f1 == f2, this might not be true anymore at some point later in time (so Fractions can't be keys in a Map<Fraction, ?> anymore ...
    A Fraction object just takes 8 bytes of memory (two ints) and then some; they won't start a garbage collection soon.

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  16. #16
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Fraction Class equals method issue

    Quote Originally Posted by JosAH View Post
    It would be silly to make them mutable; for one thing: it can screw up their 'natural' order; if f1 == f2, this might not be true anymore at some point later in time (so Fractions can't be keys in a Map<Fraction, ?> anymore ...
    A Fraction object just takes 8 bytes of memory (two ints) and then some; they won't start a garbage collection soon.

    kind regards,

    Jos
    I'm presuming you agreed with me (I did say immutable). It also allows a one time creation of the hashcode.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  17. #17
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Fraction Class equals method issue

    Quote Originally Posted by jim829 View Post
    I'm presuming you agreed with me (I did say immutable). It also allows a one time creation of the hashcode.
    Yep, I was being affirmative for once; a Fraction acts like a number; int and doubles (and their wrappers) aren't mutable either (for a very good reason).

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

Similar Threads

  1. fraction class
    By ericgomez7 in forum New To Java
    Replies: 1
    Last Post: 05-06-2013, 09:36 PM
  2. Jframe form issue, calling a method from another class
    By maaaaarco in forum AWT / Swing
    Replies: 11
    Last Post: 09-26-2012, 12:27 AM
  3. Issue in method anonymous class in GWT
    By ankit01 in forum GWT
    Replies: 0
    Last Post: 05-16-2011, 11:25 AM
  4. Decimal to Fraction method
    By Chasingxsuns in forum New To Java
    Replies: 2
    Last Post: 07-16-2009, 02:42 AM
  5. Object class's equals() method behavior????
    By skyineyes in forum New To Java
    Replies: 4
    Last Post: 07-19-2008, 11:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •