A program that tutors the user with Addition - c#

I 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.

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");
}
}

[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

Related

new to programing trying to make a number guessing game in c#

Hi so I am new to programing I just started school and I wanted to get a head start on programing so please keep in mind that everything I show you is all self-taught. Here is my question I wanted to make a random number guessing game and for the most part it works but every time you click the button to guess it randoms a different number which I don’t want here is what I have so far
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// number of guesses
int numberOfGesses = 0;
private void btnCalc_Click(object sender, EventArgs e)
{
// make the generator
Random generator = new Random();
//make the number
int number = generator.Next(1, 10);
// get the users guess
int guess = int.Parse(txtInput.Text);
//check the users guess
if (guess == number)
{
lblAnswer.Text = "You got it";
numberOfGesses = 0;
}
else if (guess != number)
{
numberOfGesses = numberOfGesses + 1;
lblAnswer.Text = "try agian you have gessed" + (numberOfGesses) + " times";
}
}
}
I know it keeps creating a new number because every time I press the guess button it starts from the top and makes a new number. I tried to take this block and make it global but I got an error
// make the generator
Random generator = new Random();
//make the number
int number = generator.Next(1, 10);
again im realy new and i found this site when lookinging up some qeustions i had so i thought it would be a good place to help me learn about programing while i wait till i can get into the programing classes thank you for your time.
You likely got an error because C# doesn't allow you to assign a default value of a field based on another field.
public partial class Form1 : Form {
int numberOfGuess = 0;
Random generator = new Random();
int number;
// other methods
}
generator can be initialized before or after number, hence the error. Instead, you can put it in the form intializer (Form1 method), or make another button and click it and generate a new random number:
public partial class Form1 : Form
{
// number of guesses
int numberOfGesses = 0;
Random generator = new Random();
int number;
public Form1()
{
InitializeComponent();
// Generate the random number
number = generator.Next(1, 10);
}
private void btnRandom_Click(object sender, EventArgs e)
{
// Generate a new random number when you click a button on the form
number = generator.Next(1, 10);
}
private void btnCalc_Click(object sender, EventArgs e)
{
// get the users guess
int guess = int.Parse(txtInput.Text);
//check the users guess
if (guess == number)
{
lblAnswer.Text = "You got it";
numberOfGesses = 0;
}
else if (guess != number)
{
numberOfGesses = numberOfGesses + 1;
lblAnswer.Text = "try agian you have gessed" + (numberOfGesses) + " times";
}
}
}
You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that generator will be initialized before number, so the above line might throw a NullReferenceException.
So change the default number value to 0:
Random generator = new Random();
int number = 0;
Initialise in the constructor:
public Form1()
{
InitializeComponent();
number = generator.Next(1, 10);
}
When the button is clicked generate the number since here you will be needing it:
private void btnCalc_Click(object sender, EventArgs e)
{
//take the input & Compare as before.
}

counter for attempts in c#

I am trying to get the counter named "Guesses" to keep a tally of attempts at guessing a random number and output the total attempts at guessing the number. I have tried leaving the counter declaration at 0 and 1 and the number of attempts to guess is always 0 or 1. Help would be appreciated and I will re-post entire working code once it's figured out. Here is my code.
int Answer; // declares the Answer variable outside button event
public frmGuess()
{ // generates random number outside button event so does not change on button click
InitializeComponent();
Random rand = new Random();
Answer = rand.Next(100) + 1; // makes it range 1 to 100
}
private void btnGuess_Click(object sender, EventArgs e)
{
int UserGuess;
int Guesses = 0; // start counter
if (string.IsNullOrEmpty(txtGuess.Text)) // input validation check to make sure not blank and is a whole number integer
{
MessageBox.Show("Please enter a whole number between 1 and 100");
return;
}
else
{
UserGuess = int.Parse(txtGuess.Text); // variable assign and code run
Guesses ++;
if (UserGuess > Answer)
{
txtGuess.Text = "";
lblAnswer.Text = "Too high, try again.";
}
else if (UserGuess < Answer)
{
txtGuess.Text = "";
lblAnswer.Text = "Too low, try again.";
}
else
{
lblAnswer.Text = "Congratulations the answer was " + Answer + "!\nYou guessed the number in " + Guesses + " tries.\nTo play again click the clear button."; //victory statement
}//end if
} //end if
}
private void btnClear_Click(object sender, EventArgs e) // clears Answer label and Guess textbox
{
txtGuess.Text = "";
lblAnswer.Text = "";
}
private void btnExit_Click(object sender, EventArgs e) // closes window
{
this.Close();
}
}
}`
Yes indeed! That took care of it. To think I placed the random number outside the button click but didn't do it to the counter - foolishness. Thanks all! Working code is :
{
int Answer; // declares the Answer variable outside button event
int Guesses = 0; // declares counter outside button event
public frmGuess()
{ // generates random number outside button event so does not change on button click
InitializeComponent();
Random rand = new Random();
Answer = rand.Next(100) + 1; // makes it range 1 to 100
}
private void btnGuess_Click(object sender, EventArgs e)
{
int UserGuess;
if (string.IsNullOrEmpty(txtGuess.Text)) // input validation check to make sure not blank and is a whole number integer
{
MessageBox.Show("Please enter a whole number between 1 and 100");
return;
}
else
{
UserGuess = int.Parse(txtGuess.Text); // variable assign and code run
Guesses ++; // adds 1 to attempts but doesn't count textbox blank or mistyping
if (UserGuess > Answer)
{
txtGuess.Text = "";
lblAnswer.Text = "Too high, try again.";
Guesses++;
}
else if (UserGuess < Answer)
{
txtGuess.Text = "";
lblAnswer.Text = "Too low, try again.";
Guesses++;
}
else
{
lblAnswer.Text = "Congratulations the answer was " + Answer + "!\nYou guessed the number in " + Guesses + " tries.\nTo play again click the clear button.";
}//end if
} //end if
}
private void btnClear_Click(object sender, EventArgs e) // clears Answer label and Guess textbox
{
txtGuess.Text = "";
lblAnswer.Text = "";
}
private void btnExit_Click(object sender, EventArgs e) // closes window
{
this.Close();
}
}
}
`
You are resetting the counter in your click event.
int Answer; // declares the Answer variable outside button event
int Guesses = 0; // declare this outside button event, and initialize it to 0.
// initialization will happen when the Form object is created.
...
private void btnGuess_Click(object sender, EventArgs e)
{
int UserGuess;
// DO NOT reset the counter here. This line is the culprit that
// resets the counter every time you click the button
//int Guesses = 0; // start counter
...
}
...
It's a scoping issue. You currently define guesses within your event handler where it resets the counter with each button click. If you define it at the form level, even as a property or member variable, that scope will allow the variable to retain its value through multiple button click events.

Store textbox value into a string?

I am making a random number generator in a form application and the user will type a number in a text box. When user clicks on the OK button. the text in the textbox will be stored in a string value. for example;
if (ButtonOK is clicked)
{
String a = textbox1;
int b = int.Parse(a);
}
Then the value of the textbox will become a labels value. for example:
b = label1.Text;
how do i do that?
I would be really happy if anyone could help me solve this problem.
SOLVED thanks to Soner Gönül
I feel like you need something like;
private void ButtonOK_Click(object sender, EventArgs e)
{
string a = textbox1.Text;
int b;
if (Int32.TryParse(a, out b))
{
label1.Text = b.ToString();
}
}
Assuming is a WinForm application just drag a button and a textbox on the form, double click on the button and write this code:
private void button1_Click(object sender, EventArgs e)
{
int max;
if (!int.TryParse(textBox1.Text, out max))
{
label1.Text = "Not a number";
}
else
{
Random r = new Random();
int random = r.Next(max);
label1.Text = string.Format("Random number: {0}", random);
}
}

asp.net submit process

i have a form with 2 labels initializing random numbers and a text box to check if the answer is correct after adding the two random numbers. The problem i am having is SUBMIT processes the next set of random numbers and so the result is always incorrect. here is the code i have so far.
namespace _2ndGradeMath
{
public partial class Default : System.Web.UI.Page
{
Random random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
int num1 = int.Parse(lblNum1.Text);
int num2 = int.Parse(lblNum3.Text);
lblAnswer.Text = (num1 + num2).ToString();
lblAnswer.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != lblAnswer.Text)
{
Button1.Attributes.Add("onClick", "javascript:alert('Incorrect');");
}
else if (TextBox1.Text == lblAnswer.Text)
{
Button1.Attributes.Add("onClick", "javascript:alert('Correct');");
}
TextBox1.Text = "";
}
}
}
Use IsPostBack to only run the initializing code when the page is initially loaded:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
int num1 = int.Parse(lblNum1.Text);
int num2 = int.Parse(lblNum3.Text);
lblAnswer.Text = (num1 + num2).ToString();
lblAnswer.Visible = false;
}
}
Here's the problem. You are loading new random numbers each time the page loads. That's what the Page_Load function does: it runs each time the page loads which includes every time the page is submitted. So when a user presses submit new random numbers are assigned, which makes his answer wrong. You need to assign random numbers in only two instances:
First, when the page loads for the first time. Which can be done by checking the property IsPostBackis false.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack){
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
}
.
.
.
}
Second, when the user answers correctly.
else if (TextBox1.Text == lblAnswer.Text)
{
Button1.Attributes.Add("onClick", "javascript:alert('Correct');");
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
}
Consider adding this code to PreRender:
protected override void OnPreRender(EventArgs e)
{
Session["Answer"] = lblAnswer.Text;
base.OnPreRender(e);
}
and then in the Click grab the answer from Session like this:
if (TextBox1.Text != Session["Answer"])
and bear in mind I'm assuming that you actually want to generate new numbers on every post back with this answer.

How to let the application check a users input?

I am making an Addition Tutoring sample, and I cannot finds ways to check for a user's input. I know there are ways where you could do a compare contrast on little things like, when a student's grade is 90-100, maybe you could apply a MessageBox.Show indicating that this student's grade is considered as an A in most cases. But, I cannot figure out which attempt to use when you are checking for an addition's sum. Like, the snippet below will generate new problems for a user to work on.
private void Newproblem_Click(object sender, EventArgs e)
{
Random Numbers = new Random();
int number1;
int number2;
int Sum;
number1 = Numbers.Next(400) + 101;
number2 = Numbers.Next(400) + 101;
theproblemLabel.Text = number1 + " + " + number2.ToString();
}
But I want to be able to check a user's answers as well. Will someone provide me an approach on how to make that happen? I will greatly appreciate any hints anyone could give me.
A better way would be to use a textbox for the question and another textbox for the answer.
Btw if you have used the properties before, you could use the property: ReadOnly and set it to true, so the user cannot modify the problem.
Layout with different situations:
Example:
//Declare variables so you can use them globally
int number1, number2, sum, userSolution;
Random numbers;
private void btnProblem_Click(object sender, EventArgs e)
{
numbers = new Random();
number1 = numbers.Next(400) + 101;
number2 = numbers.Next(400) + 101;
sum = number1 + number2;
txtProblem.Text = number1 + " + " + number2;
}
private void btnSolution_Click(object sender, EventArgs e)
{
// You try to parse the text to a integer,
// if it works its stored in userSolution,
// If it fails, it shows the messagebox
if (!int.TryParse(txtSolution.Text, out userSolution))
{
MessageBox.Show("Input is not a valid number.");
}
else
{
// Check user solution and compare it to the sum
if (userSolution == sum)
{
MessageBox.Show("Correct!", "Problem Solved!");
}
else
{
MessageBox.Show("Not Correct.", "Please try again.");
}
}
}
You could store the answer in the Tag property of the textbox
number1 = Numbers.Next(400) + 101;
number2 = Numbers.Next(400) + 101;
int answer = number1 + number2;
theproblemLabel.Text = string.Format("{0} + {1}", number1, number2);
theproblemLabel.Tag = answer;
then, when the user clicks a button to confirm its answer, you check against the stored Tag
private void Answer_Click(object sender, EventArgs e)
{
int userAnswer;
if(!Int32.TryParse(txtAnswer.Text, out userAnswer))
MessageBox.Show("Please enter a number!");
else
{
if(userAnswer == Convert.ToInt32(theproblemLabel.Tag))
MessageBox.Show("Correct answer!");
else
MessageBox.Show("Wrong answer, try againg!");
}
}
I am supposing you have a TextBox called txtAnswer where the user types its answer and a button called Answer clicked to confirm the answer

Categories

Resources