CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Hybrid View

  1. #1
    Join Date
    Apr 2014
    Posts
    6

    Fraction Calculator class and program

    Hello all, been lurking here for several weeks, first time poster.

    I am in an advanced Visual C# class (using .net 4.0). A recent assignment was to create a class to do math operations with fractions, and a windows forms application to demonstrate it. Now, I think I have the math operations done correctly (in that the math should provide a correct answer) but the program is not behaving as I expected. When the program calls on of the math methods in my fraction class, it either hangs completely, forcing me to terminate the program, or outputs an incorrect result. I've attached my code here :FractionCalculator_-_Michael_Kestner-2014-04-11.zip Before anybody asks, the instructor specified the method headers to be used in the Fraction class, based on what I've seen while searching for answers, they're a bit unusual.

    I think the problem is partly that there's no way to change a fraction's properties once it's been created. For example, I'm pretty sure the program is hanging when I do something like
    Code:
    Fraction thirdFrac = new Fraction();
    then later trying to change it like this :
    Code:
     thirdFrac = firstFrac.Add(secondFrac);
    because it can't actually do what I'm telling it to do. Again, the instructor specified read-only properties, otherwise I think this would be pretty easy to fix. I'm just drawing a blank on how to work around this issue. Any advice would be appreciated.

  2. #2
    Join Date
    Apr 2014
    Posts
    6

    Re: Fraction Calculator class and program

    Just realized it might be easier to post some of the code I'm having issues with, instead of expecting everyone to download my code.

    Here's the constructor for my class :
    Code:
    namespace FractionCalculator___Michael_Kestner{
        public class Fraction
        {
            private int _Numerator;
            private int _Denominator;
            public Fraction(int theNumerator, int theDenominator)
            {
    
    
                _Numerator = theNumerator;
                _Denominator = theDenominator;
    
    
                if (_Numerator == 0)
                {
                    throw new System.ArgumentException("Parameter cannot be Zero!", "numerator");
                }
                else if (_Denominator == 0)
                {
                    throw new System.ArgumentException("Parameter cannot be Zero!", "denominator");
                }
                else
                {
                    Reduce(_Numerator, _Denominator);//calls the reduce method, reduces fraction to simplest terms.
                }//end else
            }//end constructor
    Properties (read only)
    Code:
            public int Numerator//read only property for numerator        {
                get
                {
                    return _Numerator;
                }
            }//end Numerator
            public int Denominator//read only property for denominator
            {
                get
                {
                    return _Denominator;
                }
            }//end Denominator
    Here's one of the Math functions (the other ones have similar headers)
    Code:
      public Fraction Add(Fraction rightFrac)        {
                Fraction result = new Fraction((this.Numerator * rightFrac.Denominator) + (rightFrac.Numerator * this.Denominator),
                                      this.Denominator * rightFrac.Denominator);
    
    
                
                return result;
            }

    This is where the application that uses the class normally hangs (The app uses a combo box with operators to select which operation to perform)
    Code:
    if(operationComboBox.SelectedIndex == 1)
                {
                    thirdFrac = firstFrac.Add(secondFrac);
                     
    
    
                }

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Fraction Calculator class and program

    Btw, if you don't know how to set a breakpoint and step through your code, please ask.

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Fraction Calculator class and program

    The reason it's hanging is that you have bugs in the Fraction GCF and Reduce methods.

    Besides that, you can simply your code and eliminate the code related to string validation and parsing by restricting the textboxes to only take integers.

    In addition, you can simplify the equals button code, by disabling it when the form starts up and enabling it when all four text boxes have numbers and the user has selected an operation from the combobox.

    Code:
            private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                EnableEqualsButton();
            }
    
            private void OnTextChangeValidateInteger(object sender, EventArgs e)
            {
                var textBox = (TextBox) sender;
    
                try
                {
                    if (textBox.Text != "-")
                    {
                        var x = int.Parse(textBox.Text);
                    }
                }
                catch (Exception)
                {
                    try
                    {
                        var cursorIndex = textBox.SelectionStart - 1;
                        textBox.Text = textBox.Text.Remove(cursorIndex, 1);
    
                        //Align Cursor to same index
                        textBox.SelectionStart = cursorIndex;
                        textBox.SelectionLength = 0;
                    }
                    catch (Exception)
                    {
                    }
                }
    
                EnableEqualsButton();
            }
    
            private void EnableEqualsButton()
            {
                equalsButton.Enabled = (!String.IsNullOrEmpty(firstNumBox.Text)
                                        && !String.IsNullOrEmpty(firstDenomBox.Text)
                                        && !String.IsNullOrEmpty(secondNumBox.Text)
                                        && !String.IsNullOrEmpty(secondDenomBox.Text)
                                        && operationComboBox.SelectedIndex != -1);
            }
    
            private void equalsButton_Click(object sender, EventArgs e)
            {
                Fraction thirdFrac;
    
                var firstFrac = new Fraction(Int32.Parse(firstNumBox.Text), Int32.Parse(firstDenomBox.Text));
                var secondFrac = new Fraction(Int32.Parse(secondNumBox.Text), Int32.Parse(secondDenomBox.Text));
                
                if (operationComboBox.SelectedIndex == 1)
                {
                    thirdFrac = firstFrac.Add(secondFrac);
                }
                else if (operationComboBox.SelectedIndex == 2)
                {
                    thirdFrac = firstFrac.Subtract(secondFrac);
                }
                else if (operationComboBox.SelectedIndex == 3)
                {
                    thirdFrac = firstFrac.Multiply(secondFrac);
                }
                else
                {
                    thirdFrac = firstFrac.Divide(secondFrac);
                }
    
                //start output
                //Assign the third fractions numerator and denominator to int variables
                outNumLabel.Text = thirdFrac.Numerator.ToString(CultureInfo.InvariantCulture);
                outDenomLabel.Text = thirdFrac.Denominator.ToString(CultureInfo.InvariantCulture);
                outFloatStringLabel.Text = thirdFrac.ToFloatString(3);
            }
    In the code above, I have set the TextChange events of each of the textboxes to OnTextChangeValidateInteger() handler (the code of which I found on the internet).
    I also set the operation combox selection change to the EnableEqualButton() method.

    To further figure out what is going on in your code, set a breakpoint in the Fraction class constructor (put the cursor in the constructor and press F9). Then step through the code. The hang occurs in the GCG method - there is a while loop which you never exit from. Another bug is your Reduce method never [re]sets the _Numerator and _Denominator fields.

  5. #5
    Join Date
    Apr 2014
    Posts
    6

    Re: Fraction Calculator class and program

    Thanks for the advice, arjay! My instructor doesn't allow us to restrict our textboxes for validation purposes. His theory is if you get used to using those features, you won't know what to do if you're coding in an environment that doesn't have them. I'm working with some artificial constraints since this is for a college class.

    I do know how to set up break points, that's how I determined where the winforms app was hanging. It never occured to me to double check the code in my fraction class. Hubris, I suppose. Thanks again!

  6. #6
    Join Date
    Apr 2014
    Posts
    6

    Re: Fraction Calculator class and program

    Quote Originally Posted by kestnuts View Post
    Thanks for the advice, arjay! My instructor doesn't allow us to restrict our textboxes for validation purposes. His theory is if you get used to using those features, you won't know what to do if you're coding in an environment that doesn't have them. I'm working with some artificial constraints since this is for a college class.
    Actually, ignore this. I misunderstood what you were saying. My mistake.

  7. #7
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Fraction Calculator class and program

    Quote Originally Posted by kestnuts View Post
    Actually, ignore this. I misunderstood what you were saying. My mistake.
    No problem. With regard to the instructor stating
    My instructor doesn't allow us to restrict our textboxes for validation purposes. His theory is if you get used to using those features, you won't know what to do if you're coding in an environment that doesn't have them.
    .

    While I understand the instructor's point, one important thing to learn is to understand what is available in an environment and be able to leverage it rather than writing extra code for functionality that is already built-in.

  8. #8
    Join Date
    Apr 2014
    Posts
    6

    Re: Fraction Calculator class and program

    I would tend to agree. That being said, I really don't want to lose points over what he would probably view as "cheating".

    I found and fixed the bug in my GCF method. I refactored it slightly from an older project and forgot to rename some of the variables. Now I've found a bug in my addition method. It works except when the numerator or denominator (or both) of either fraction is 1. I'm going to have to redo that algorithm.

  9. #9
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Fraction Calculator class and program

    Quote Originally Posted by kestnuts View Post
    I would tend to agree. That being said, I really don't want to lose points over what he would probably view as "cheating".
    Sure, you have to follow the constraints of the instructor. In the real world, leveraging what is available in the environment is considered coding smartly, not cheating.

  10. #10
    Join Date
    Apr 2014
    Posts
    6

    Re: Fraction Calculator class and program

    Quote Originally Posted by Arjay View Post
    Sure, you have to follow the constraints of the instructor. In the real world, leveraging what is available in the environment is considered coding smartly, not cheating.
    Agreed! I firmly believe in working smarter, not harder. Thanks again for all your help.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured