How to let the application check a users input? - c#

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

Related

A program that tutors the user with Addition

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

How Can You Calculate Multiple Textboxes?

I need help with my program in Visual Studio C#. The user must be able to enter a value into the four blank textboxes. The numbers in the textboxes should multiply with their set prices when the user clicks on Calculate. In other words, I want the four textboxes to multiply with their price.
The Form
Here's the calculation code. I managed to get the Children 5-12 textbox to calculate.
private void btnCalculate_Click (object sender, EventArgs e)
{
int FirstTextBoxNumber;
int SecondTextBoxNumber;
int answer;
try
{
Convert.ToInt32(tbSecondNumber.Text);
FirstTextBoxNumber = int.Parse("2");
SecondTextBoxNumber = int.Parse(tbSecondNumber.Text);
answer = FirstTextBoxNumber * SecondTextBoxNumber;
MessageBox.Show("Your total is £" + answer.ToString());
}
catch (FormatException)
{
MessageBox.Show("Please enter a decimal value");
}
}
How the form calculates
Try the following inside your btnCalculate_Click code:
bool isNumeric = true;
double answer = 0;
double firstTextBoxNumber = 0;
double thirdTextBoxNumber = 0;
double fifthTextBoxNumber = 0;
double seventhTextBoxNumber = 0;
int secondTextBoxNumber = 0;
int fourthTextBoxNumber = 0;
int sixTextBoxNumber = 0;
int eightTextBoxNumber = 0;
try
{
if (String.IsNullOrWhiteSpace(tbFirstNumber.Text) || String.IsNullOrWhiteSpace(tbSecondNumber.Text) || String.IsNullOrWhiteSpace(tbThirdNumber.Text) || String.IsNullOrWhiteSpace(tbFourthNumber.Text) || String.IsNullOrWhiteSpace(tbFifthNumber.Text) || String.IsNullOrWhiteSpace(tbSixNumber.Text) || String.IsNullOrWhiteSpace(tbSeventhNumber.Text) || String.IsNullOrWhiteSpace(tbEightNumber.Text))
{
isNumeric = false;
}
else
{
//Check if "Prices" are all Doubles
if (isNumeric)
{
isNumeric = double.TryParse(tbFirstNumber.Text.Replace("£", ""), out firstTextBoxNumber);
}
if (isNumeric)
{
isNumeric = double.TryParse(tbThirdNumber.Text.Replace("£", ""), out thirdTextBoxNumber);
}
if (isNumeric)
{
isNumeric = double.TryParse(tbFifthNumber.Text.Replace("£", ""), out fifthTextBoxNumber);
}
if (isNumeric)
{
isNumeric = double.TryParse(tbSeventhNumber.Text.Replace("£", ""), out seventhTextBoxNumber);
}
//Check if "Qty" are all Integers
if (isNumeric)
{
isNumeric = int.TryParse(tbSecondNumber.Text, out secondTextBoxNumber);
}
if (isNumeric)
{
isNumeric = int.TryParse(tbFourthNumber.Text, out fourthTextBoxNumber);
}
if (isNumeric)
{
isNumeric = int.TryParse(tbSixNumber.Text, out sixTextBoxNumber);
}
if (isNumeric)
{
isNumeric = int.TryParse(tbEightNumber.Text, out eightTextBoxNumber);
}
}
if (isNumeric)
{
answer = firstTextBoxNumber * secondTextBoxNumber;
answer += thirdTextBoxNumber * fourthTextBoxNumber;
answer += fifthTextBoxNumber * sixTextBoxNumber;
answer += seventhTextBoxNumber * eightTextBoxNumber;
MessageBox.Show("Your total is £" + answer.ToString());
}
else
{
MessageBox.Show("Please enter a decimal value");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The Try Catch block was changed because you should only handle system errors in Try blocks.
Please do note, I made the following assumptions:
The price can change, and can be changed to include cents and fractions of cents.
The price will only remove "£" and no other currency logos.
The Qty will always be an int since you can't have 1.5 children.
You are ok with the system error being shown in a message box to the
user instead of being logged somewhere.
Since this was quick, the code could be expanded on to remove some of the assumptions and to add rounding.
OK. I'm going to try to explain it to you:
You have 8 textboxes in your form.
They all have an identifier like textBox1, textBox2 etc..
What you want to take textBox1 and multiply it by textBox2. And this the same for the other 3 pairs. Then add up the total and display it in a messageBox.
I'll try to send you the right way:
private void btnCalculate_Click (object sender, EventArgs e)
{
int FirstPrice, SecondPrice, ThirdPrice, FourthPrice;
int FirstQnty, SecondQnty, ThirdQnty, FourthQnty;
int answer = 0;
try
{
FirstPrice = (int)TextBox1.Text.Replace("£", "");
SecondPrice = (int)TextBox2.Text;
ThirdPrice = (int)TextBox3.Text.Replace("£", "");
FourthPrice = (int)TextBox4.Text;
FirstQty = (int)TextBox5.Text.Replace("£", "");
SecondQty = (int)TextBox6.Text;
ThirdQty = (int)TextBox7.Text.Replace("£", "");
FourthQty = (int)TextBox8.Text;
answer = FirstPrice * FirstQty;
answer += SecondPrice * SecondQty;
answer += ThirdPrice * ThirdQty;
answer += FourthPrice * FourthQty;
MessageBox.Show("Your total is £" + answer.ToString());
}
catch (FormatException)
{
MessageBox.Show("Please enter a decimal value");
}
}
It might contain some spelling errors, but it should work.
Just replace the TextBox identifiers to the ones in your form.

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

error Input string was not in a correct format in the first line int a

private void txtrate_TextChanged(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtqty.Text);
int b = Convert.ToInt32(txtrate.Text);
int c = a * b;
txttotal.Text = Convert.ToString(c);
//txttotal.Text = (Convert.ToInt32(txtqty.Text) * Convert.ToInt32(txtrate.Text)).ToString();
}
Well... this error occurs of txtqty.Text (or txtrate.Text for variable b) does not contain a valid number. So the user entered letters or other characters instead of 0 till 9.
You could try to validate your input first with TryParse:
private void txtrate_TextChanged(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtqty.Text);
int b = Convert.ToInt32(txtrate.Text);
if (Int32.TryParse(txtqty.Text, out a) && (Int32.TryParse(txtrate.Text, out b)
{
int c = a * b;
txttotal.Text = c.ToString();
}
}
Yes, this is due to the value not contained only numbers, to avoid this situation, please setup the type of data you are trying to collect with the text fields, you can setup refer this post for a detailed walk through on how to do it.
Yes, I would suggest TryParsetoo :
private void txtrate_TextChanged(object sender, EventArgs e)
{
int number;
bool result = Int32.TryParse(txtqty.Text, out number);
if (result)
{
//Converting is Ok, proceed
}
else
{
//Convertign fail
txtqty.Focus();
MessageBox.Show("Please enter only number for this field");
return;
}
}
I would suggest making this for each textbox with setting the focus to the textbox with incorrect input and providing an useful message for the user. In my opinion this is a suitable and user-friendly way.

Categories

Resources