Home > Software engineering >  Check answer button has incorrect input string format
Check answer button has incorrect input string format

Time:10-04

I am trying to create a check answer button. I have not learned how to use methods yet so i cannot use them in this. I first need to check if the math operation is subtraction or addition and then go from there. Visual studio does not detect any errors but when i run the program and try to check the answer ive inputted i get an error telling me unhandled exception has occured and that input string was not in correct format. I have a feeling the proble is with my int lblMath but im not sure how else to check what the value is inside of that lbl.

 {
            int First = int.Parse(lblFirst.Text);//The first number in the math equation
            int Second = int.Parse(lblSecond.Text);//The second number in the math equation
            int UserAnswer = Convert.ToInt32(txtAnswer.Text);//The users answer to math question
            int lblMath = int.Parse(lblMathType.Text);//Whether the symbol is   or -
            if(lblMath == ' ')
            {
                int AnswerAdd = First   Second;
                //Answer is addition
                if(UserAnswer == AnswerAdd)
                {
                    MessageBox.Show("Correct");
                }
                else if(UserAnswer != AnswerAdd)
                {
                    MessageBox.Show("Wrong Answer");
                }
            }
            else if (lblMath == '-')
            {
                int AnswerSub = First - Second; 
                //Answer is subtraction
                if(UserAnswer == AnswerSub)
                {
                    MessageBox.Show("Correct");
                }
                else if (UserAnswer != AnswerSub)
                {
                    MessageBox.Show("Wrong Answer");
                }

            }
        

CodePudding user response:

You're expecting this to be an integer:

int lblMath = int.Parse(lblMathType.Text);

But then you're immediately expecting it to be a string:

if(lblMath == ' ')

(I'm honestly surprised this even compiles.)

What integer value to you expect the string " " to be and why? The exception is telling you that the string " " is not an integer. Because it isn't.

It's a string. Use it as a string:

string lblMath = lblMathType.Text;
  •  Tags:  
  • c#
  • Related