Results 1 to 13 of 13
Like Tree2Likes
  • 2 Post By JosAH

Thread: Fractions equals each other problem

  1. #1
    LetsG0Blue is offline Member
    Join Date
    Feb 2013
    Posts
    68
    Rep Power
    0

    Default Fractions equals each other problem

    Everything else works fine besides this equals code could somebody check it out for me? and point me in the right direction?

    Java Code:
    public boolean equals(Fractions f)
         {
        	 int X = num, X1 = denom, Y = f.num, Y1 = f.denom;
        	 
        	 if (X/X1 == Y/Y1)
                 return false;
        	 else             
                 return true;
         }

    Java Code:
    import java.util.*;
    
    public class Fractions
    {
        private Scanner scan = new Scanner(System.in);     
        private int num=1;
        private int denom=1;
        
        public Fractions()
        { 
        }
        
        public Fractions(int n, int d)
        {
            num = n;
            denom = d;
            reduce();
        }
        
        public void setFraction(int n, int d)
        {
        	num = n;
            denom = d;
            reduce();
        }
    
        public Fractions add(Fractions op)
        {
        	int a = num, b = denom, c = op.num, d = op.denom;
    
        	int num_new = a*d + b*c, denom_new = b*d;
    
        	Fractions f = new Fractions(num_new, denom_new);
    
        	return f;
        }  
    
        public Fractions subtract(Fractions op)
        {	
        	int a = num, b = denom, c = op.num, d = op.denom;
    
        	int num_new = a*d - b*c, denom_new = b*d;
    
        	Fractions f = new Fractions(num_new, denom_new);
    
        	return f;
        } 
    
        public Fractions multiply(Fractions op)
        {
        	int a = num, b = denom, c = op.num, d = op.denom;
    
        	int num_new = a*c, denom_new = b*d;
    
        	Fractions f = new Fractions(num_new, denom_new);
    
        	return f;
        }  
    
        public Fractions divide(Fractions op)
        {
        	int a = num, b = denom, c = op.num, d = op.denom;
    
        	int num_new = a*d, denom_new = b*c;
    
        	Fractions f = new Fractions(num_new, denom_new);
    
        	return f;
        }  
         
         
         private void reduce()
         {
         int smaller = Math.min(Math.abs(num), Math.abs(denom));
         for (int divisor = 2; divisor < smaller; divisor++)
         {
        	 while ( (num % divisor == 0) && (denom % divisor == 0))
        	 {
        		 num = num / divisor;
        		 denom /= divisor;
        		 smaller /= divisor;
        	 }
         }
         	 }
         public boolean equals(Fractions f)
         {
        	 int X = num, X1 = denom, Y = f.num, Y1 = f.denom;
        	 
        	 if (X/X1 == Y/Y1)
                 return false;
        	 else             
                 return true;
         }
         
         public String toString()
         {
            return num + "/" + denom;
         }
         
         public void readin(String label)
         {
            while (true) // Keep trying if bad input is received
            {
                System.out.println(label);
                String temp = scan.next();
                temp = temp.trim(); // get rid of white space at the beginning and end
                int index = temp.indexOf('/');
                if (index >= 0)
                {
                    String numStr = temp.substring(0, index);
                    String denomStr = temp.substring(index+1);
                    int n = Integer.parseInt(numStr);
                    int d = Integer.parseInt(denomStr);
                    setFraction(n,d);
                    return;
                }
                else
                    System.out.println("Input Fraction missing / ");
            }//Keep trying until you get it right
         }
         
         public static void main(String[] args)
         {
            Fractions f1= new Fractions();
            Fractions f2= new Fractions();
            Fractions f3=null;
            Scanner scan = new Scanner(System.in);
            
            while(true)
            {
                System.out.println("Enter operation: + - * / q (q ==> quit) : ");
                String input = scan.next();
                if (input.charAt(0) == 'q') return; // All done
                
                f1.readin("Enter Fraction 1: ");
                f2.readin("Enter Fraction 2: ");
                System.out.println("f1 = " + f1);
                System.out.println("f2 = " + f2);
                
                if (f1.equals(f2))
                    System.out.println("f1 and f2 are equal");
                else
                    System.out.println("f1 and f2 are not equal");
                
                switch (input.charAt(0))
                {                
                case '+':
                    f3 = f1.add(f2);
                    System.out.println("f1+f2=" + f3);
                break;
    
                case '-':
                    f3 = f1.subtract(f2);
                    System.out.println("f1-f2=" + f3);
                    break;
    
                case '*':
                    f3 = f1.multiply(f2);
                    System.out.println("f1*f2="+f3);
                    break;
    
                case '/':
                    f3 = f1.divide(f2);
                    System.out.println("f1/f2="+f3);
                    break;
    
                default:
                    System.out.println("Illegal command: "  + input );
                    break;
    
                }
            }// end of while loop
             
         }  // end of main 
     }

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    2,935
    Rep Power
    4

    Default Re: Fractions equals each other problem

    You are using ints instead of doubles for your fractions. Thus anything to the right of the decimal point is discarded.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    angstrem is offline Member
    Join Date
    Mar 2013
    Posts
    11
    Rep Power
    0

    Default Re: Fractions equals each other problem

    Yes, the int/int division gives int in the result. I suppose, the most convenient solution here would be casting.
    Java Code:
    if ((double) X/X1 == (double) Y/Y1)
                 return false;
             else            
                 return true;
    The (double) part tells, that X must be treated as a double. and double/int division gives double in a result.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    2,935
    Rep Power
    4

    Default Re: Fractions equals each other problem

    That won't work either because X/X1 is evaluated as an int and then you convert it to a double. The best method would be to use doubles everywhere in place of ints (based on my assumption of what you are trying to do).

    A couple more observations. Your equals method is a method of the Fraction class. So a typical approach would be to pass in the num and denom as arguments and use the instance variables for the other num and denom.

    And as you get more into Java, you should get into the habit of overriding hashCode if you override equals. Otherwise, the various hashMaps and such will not perform properly.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default Re: Fractions equals each other problem

    Quote Originally Posted by jim829 View Post
    That won't work either because X/X1 is evaluated as an int and then you convert it to a double.
    Nope.
    Java Code:
    public class Division {
    
      public static void main(String[] args) {
        System.out.println((double) 5 / 2);
      }
    }
    Run it and see.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

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

    Default Re: Fractions equals each other problem

    Casting to double is silly: if mathematically a/b == c/d then a*d == c*b and you would need longs at worst.

    kind regards,

    Jos
    DarrylBurke and jim829 like this.
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    2,935
    Rep Power
    4

    Default Re: Fractions equals each other problem

    Hmm, I could have sworn I had done this before and it didn't work. However, I stand humbly corrected!

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

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

    Default Re: Fractions equals each other problem

    Quote Originally Posted by jim829 View Post
    Hmm, I could have sworn I had done this before and it didn't work. However, I stand humbly corrected!
    It must've been bit rot; b.t.w. a Fraction implementation with an int numerator and denominator is next to useless; e.g. look at the arithmetic operations above: if any of those multiplications make an int overflow, the result will be incorrect. A solid Fraction class implementation is a nasty beast.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    LetsG0Blue is offline Member
    Join Date
    Feb 2013
    Posts
    68
    Rep Power
    0

    Default Re: Fractions equals each other problem

    Quote Originally Posted by jim829 View Post
    That won't work either because X/X1 is evaluated as an int and then you convert it to a double. The best method would be to use doubles everywhere in place of ints (based on my assumption of what you are trying to do).

    A couple more observations. Your equals method is a method of the Fraction class. So a typical approach would be to pass in the num and denom as arguments and use the instance variables for the other num and denom.

    And as you get more into Java, you should get into the habit of overriding hashCode if you override equals. Otherwise, the various hashMaps and such will not perform properly.

    Regards,
    Jim
    Can you explain this a little further for me?

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    2,935
    Rep Power
    4

    Default Re: Fractions equals each other problem

    Well, the first part of my post was incorrect (which has been pointed out). I had gotten my operator and cast precedences bass ackwards. So something like:

    double x = (double) n/m is the same as double x = ((double) n)/m

    Here is what I meant regarding you're highlighted area (note I will be using Jos' recommendation for comparison)

    Java Code:
    class Fraction {
       int num;
       int denom;
    
       Fraction(int num, int denom) {
          this.num = num;
          this.denom = denom;
       }
    
       public boolean equals(int n, int d) {
          System.out.println("Comparing " + n + "/" + d + " to " + num + "/"
                + denom);
          return num * d == denom * n;
       }
    }
    
    public class FractionExample {
       public static void main(String[] args) {
          Fraction f1 = new Fraction(10, 15);
          Fraction f2 = new Fraction(20, 40);
    
          System.out.println(f1.equals(40, 60)); // true
          System.out.println(f1.equals(2, 4)); // false
          System.out.println(f2.equals(50, 100)); // true
          System.out.println(f2.equals(1, 3)); // false
       }
    }

    Also, in this case the hashCode recommendation doesn't apply because this signature is different than the one inherited from the Object class.

    Note: In an earlier post I discussed overriding equals. Just to clarify, you did *not* override equals because your equals signature takes an object of Fraction and not an object of Object. I hope this doesn't muddy the issue.

    Regards,
    Jim
    Last edited by jim829; 03-11-2013 at 02:30 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  11. #11
    LetsG0Blue is offline Member
    Join Date
    Feb 2013
    Posts
    68
    Rep Power
    0

    Default Re: Fractions equals each other problem

    How would you do it with my code though? I have to follow that template for class. It's the only one I don't understand because how would I use the fraction f to make it equal?

  12. #12
    LetsG0Blue is offline Member
    Join Date
    Feb 2013
    Posts
    68
    Rep Power
    0

    Default Re: Fractions equals each other problem

    figured it out.

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

    Default Re: Fractions equals each other problem

    I gave it another look: if you properly normalize the numerator and denominator and stick the sign in (say) the numerator, the equals( ... ) method simply has to compare the two numerators and denominators for equality.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Problem with my equals method
    By coasterguy10 in forum New To Java
    Replies: 3
    Last Post: 10-24-2011, 10:45 PM
  2. trouble using fractions
    By jeanOliver in forum New To Java
    Replies: 2
    Last Post: 09-06-2011, 08:48 PM
  3. Reducing fractions
    By SwEeTAcTioN in forum New To Java
    Replies: 10
    Last Post: 01-13-2010, 04:51 PM
  4. a little problem with (equals)
    By gamilah in forum New To Java
    Replies: 5
    Last Post: 10-25-2008, 04:08 AM
  5. Replies: 0
    Last Post: 01-25-2008, 11:13 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
  •