2

enter image description hereI am creating a C# application that generates two random integers,between 100 to 500. The numbers should perform addition such that

           247 + 129 = ?

The form has a text box for the user to enter the problem's answer. When a button is clicked, the application should do the following:

Check the user's input and display a message indicating whether it is the correct answer or not. Generate two new random numbers and display them in a new problem on the form add a button named "Save score to file".

When clicked, this button should write the total number of problems, the number of correct answers as well as the percentage of problems answered correctly.

Code:

InitializeComponent();

        Random rand = new Random();
        {
            int number1;

            number1 = rand.Next(400) + 100;

            numberLabel1.Text = Convert.ToString(number1);
        }
        {

            int number2;

            number2 = rand.Next(400) + 100;
            numberLabel2.Text = Convert.ToString(number2);
        }
    }

    private void checkButton_Click(object sender, EventArgs e)
    {

        int correctAnswer;
        correctAnswer = int.Parse(numberLabel1.Text) + int.Parse(numberLabel2.Text);
        int userAnswer;
        userAnswer = Convert.ToInt32(userInputBox.Text);

        if (userAnswer == correctAnswer)
        {
            MessageBox.Show("Your Answer is Correct");
        }
        else
        {
            MessageBox.Show("Your Answer is Incorrect");
        }
    }
    private void clearButton_Click(object sender, EventArgs e)
    {

        numberLabel1.Text = "";
        numberLabel2.Text = "";
        userInputBox.Text = "";
    }

    private void exitButton_Click(object sender, EventArgs e)
    {

        this.Close();
    }

    private void answerBox_TextChanged(object sender, EventArgs e)
    {

               }
}

}

The question I have is: How do I get an output? The message box isn't showing and I answer the problem correctly each time. After This how do Generate two new random numbers and display them in a new problem on the form add a button named "Save score to file".

When clicked, this button should write the total number of problems, the number of correct answers as well as the percentage of problems answered correctly.

YaBoyyy
  • 23
  • 6
  • 2
    I am very very new to stack overflow, and very new to C#. Please be gentle. – YaBoyyy Oct 05 '18 at 04:09
  • Your question is quite large...could you try reducing it a bit to the specific thing you are having trouble with? If you're having trouble with more than one thing, it's easier for us to help if you ask a separate question for each thing. – Richard Ev Oct 05 '18 at 04:21
  • @RichardEverett I am showing that I do not have errors in VS. When I go to debug, I input the correct answer which should give make a message box appear saying " Your answer is correct.". Although the right input is put in for the problem, I receive no message box. – YaBoyyy Oct 05 '18 at 04:24
  • Have you tried [setting a breakpoint](https://docs.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2017) in the `checkButton_Click` method, to verify that it is getting called? – Richard Ev Oct 05 '18 at 04:27
  • @RichardEverett Yes, I have tried this. It is getting called. – YaBoyyy Oct 05 '18 at 04:34
  • So is your actual issue that you can't get a message box to display when a button gets clicked? How about trying to get just this to work in a separate, new, application? – Richard Ev Oct 05 '18 at 04:37
  • @RichardEverett This is the second time I have started fresh with a new application. I keep encountering the same issue. – YaBoyyy Oct 05 '18 at 04:41
  • @RichardEverett I am unable to 1) Get a message box to appear after the right answer is input into the answerBox. 2)Generate two new random numbers 3)I am unable to show the number of times a user correctly answered as well as the percentage of problems answered correctly. – YaBoyyy Oct 05 '18 at 05:05
  • OK, let's look at those one-at-a-time... 1) `MessageBox.Show("testing");` in an otherwise empty "click" event handler for a button will cause a message box to be displayed. If not, something strange is happening on your machine. 2) To generate multiple random numbers, see [this existing answer](https://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number-in-c). Note that you don't need the extra { braces } around your random number code. 3) Are you having trouble showing this, or calculating it? – Richard Ev Oct 05 '18 at 05:12
  • 3) I'm having trouble on how to exactly code it. Would I write a code for it just to reappear, or would I make the user click a button to regenerate new numbers. I am just lost with this part. – YaBoyyy Oct 05 '18 at 05:16
  • (If you can wait a few hours, I'll see about adding a useful answer later on tonight) – Richard Ev Oct 05 '18 at 05:23
  • @RichardEverett That would help a tremendous amount. Please don't forget about me. Thank you so much for your help. – YaBoyyy Oct 05 '18 at 05:39
  • Looks like you have quite a few answers now...have they helped? – Richard Ev Oct 05 '18 at 12:07

3 Answers3

0

Generate two new random numbers and display them in a new problem on the form

simply copy-paste that codes that doing the job that you already wrote. doing it via method is much better:

Add this method:

private void GenerateNewQuestion()
{
       Random rand = new Random();
       {
            int number1;

            number1 = rand.Next(400) + 100;

            numberLabel1.Text = Convert.ToString(number1);
       }
       {

            int number2;

            number2 = rand.Next(400) + 100;
            numberLabel2.Text = Convert.ToString(number2);
       }
}

and then use it wherever you want:

if (userAnswer == correctAnswer)
{
     MessageBox.Show("Your Answer is Correct");

     GenerateNewQuestion();
}

add a button named "Save score to file".

You don't need to add button in run-time for your problem. Instead you can:

  1. Add the button on your form
  2. Make it's Visible property False

(you can do it with designer or add saveScoreButton.Visible = false; to your Form constructor )

  1. Make it visible wherever you want

In your case:

if (userAnswer == correctAnswer)
{
      MessageBox.Show("Your Answer is Correct");

      GenerateNewQuestion();
      saveScoreButton.Visible = true;
}

When clicked, this button should write the total number of problems, the number of correct answers as well as the percentage of problems answered correctly.

you can add counters for correct and wrong answers then use them:

add this to your form field:

int totalNumberOfProblems = 1; //when the form is opened a question will be already asked
int correctAnswers = 0;
int wrongAnswers = 0;

increase correctAnswers and wrongAnswers when receiving an answer in your checkButton_Click:

if (userAnswer == correctAnswer)
{
      MessageBox.Show("Your Answer is Correct");

      GenerateNewQuestion();
      saveScoreButton.Visible = true;
      correctAnswers++;
      totalNumberOfProblems++;

}
else
{
      MessageBox.Show("Your Answer is Incorrect");
      GenerateNewQuestion();
      saveScoreButton.Visible = true;
      wrongAnswers++;
      totalNumberOfProblems++;
}

then do the write to file part:

private void saveScoreButton_Click(object sender, EventArgs e)
{
    using (StreamWriter writer = new StreamWriter(@"C:\Users\Hüseyin\Desktop\saved scores.txt", true))
    {
        string text = $"Total number of problems: {totalNumberOfProblems-1}\r\nNumber of correct answers: {correctAnswers}\r\n";
        double ratio = (double)correctAnswers / (double)totalNumberOfProblems-1;
        text += $"Percentage: {ratio:P2}";
        writer.WriteLine(text);
        MessageBox.Show("File Saved");
    }
}
merkithuseyin
  • 468
  • 1
  • 4
  • 14
  • GenerateNewProblem doesn't show up in blue on mine as if I didn't assign it anything. and Save score button doesn't exist in current context. – YaBoyyy Oct 05 '18 at 07:05
  • did you add the `private void GenerateNewQuestion(){ ... }` method? it must be outside any other methods' and inside form class – merkithuseyin Oct 05 '18 at 07:13
  • also add the "save score button" and then double click on it. then you can write the codes in it – merkithuseyin Oct 05 '18 at 07:14
  • my whole form disappears when debugging when I do this. – YaBoyyy Oct 05 '18 at 07:17
  • I started fresh. Creating the exit button is as far as I am right now. – YaBoyyy Oct 05 '18 at 07:18
  • here are the complete codes: [link](https://dotnetfiddle.net/KpZjr6) first: you have to add the controls(textbox, labels etc.) then rename them according to code: for example one of your label name must be numberLabel1 or change the code according to your control names. lastly, fill the events and check if their names match. check winform tutorials on internet it will be helpful. – merkithuseyin Oct 05 '18 at 07:35
  • Is there a way to use it without StreamWriter? – YaBoyyy Oct 05 '18 at 07:43
  • where at exactly? I am confused. In which part of the codes? – YaBoyyy Oct 05 '18 at 07:46
  • I understand the codes, and how they work. I am just not getting on how to structure everything properly. That is my biggest issue. – YaBoyyy Oct 05 '18 at 07:47
  • Is there a way to get the scores using return? – YaBoyyy Oct 05 '18 at 07:48
  • check [link](https://dotnetfiddle.net/KpZjr6) it's on very top of codes – merkithuseyin Oct 05 '18 at 07:48
  • access to path is denied. We are using return for the scores, I believe. – YaBoyyy Oct 05 '18 at 08:00
  • I'm trying to show the score kept in a multi-line textbox. – YaBoyyy Oct 05 '18 at 08:02
0
private static Random rand = new Random();
private void checkButton_Click(object sender, EventArgs e)
{
    int num1 = rand.Next(400) + 100;
    int num2 = rand.Next(400) + 100;
    label1.Text = num1.ToString();
    label2.Text = num2.ToString();
    int correctAnswer = num1 + num2;
    int userAnswer = Convert.ToInt32(textBox1.Text);

        if (userAnswer == correctAnswer)
        {
            MessageBox.Show("Your Answer is Correct");
        }
        else
        {
            MessageBox.Show("Your Answer is Incorrect");
        }
}
  • Hi and welcome to Stack Overflow. Please try to provide an explanation when submitting code as an answer. See [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) for more information. – Ruzihm Oct 05 '18 at 07:04
-1

[First]

Console.WriteLine ( String.Format("Answer => " + userAnswer ) );

will show it on console window

MessgeBox.Show( ( String.Format("Answer => {0}", userAnswer ) );

will show it on MessageBox.

I put 2 types of how to use String.Format for you :)

[Second]

you can make a button which do the task again.

put your generating code under the button function

[Third]

You need to study about StreamWriter

S M
  • 2,939
  • 5
  • 28
  • 54
Arphile
  • 841
  • 5
  • 17
  • A minor point - in the first example, you don't need to use `string.Format`, because `"Answer => " + userAnswer` will do the job of creating the string itself. – Richard Ev Oct 05 '18 at 04:25
  • I don't quite understand just yet. I need to do this in windows forms. Which would call for MessageBox. – YaBoyyy Oct 05 '18 at 04:33