I'm confused on how to get this program to do a few certain things and a question for future reference for myself:
Question:
Can you do if statements with buttons
example: if (button1 is clicked)
do this
else if (button2 is clicked)
do this
The goal of my program is to help learn basic integer mathematics and the four sections are ADDING, SUBTRACTING, MULTIPLYING, and MOD.
I have four buttons for each one of those topics, and a fifth button to submit the answer for the question, I have 3 text boxes, the first being the question that is presented, second being the users answer, third being whether the answer was correct or not
What I currently have set up:
private void button1_Click(object sender, EventArgs e)
{
Random random1 = new Random();
int randomNumber1 = random1.Next(6, 11);
Random random2 = new Random();
int randomNumber2 = random2.Next(1, 6);
textBox1.Text = "What is " + randomNumber1 + " + " + randomNumber2 + " ?";
}
private void button2_Click(object sender, EventArgs e)
{
Random random1 = new Random();
int randomNumber1 = random1.Next(6, 11);
Random random2 = new Random();
int randomNumber2 = random2.Next(1, 6);
textBox1.Text = "What is " + randomNumber1 + " - " + randomNumber2 + " ?";
}
private void button3_Click(object sender, EventArgs e)
{
Random random1 = new Random();
int randomNumber1 = random1.Next(6, 11);
Random random2 = new Random();
int randomNumber2 = random2.Next(1, 6);
textBox1.Text = "What is " + randomNumber1 + " * " + randomNumber2 + " ?";
}
private void button4_Click(object sender, EventArgs e)
{
Random random1 = new Random();
int randomNumber1 = random1.Next(6, 11);
Random random2 = new Random();
int randomNumber2 = random2.Next(1, 6);
textBox1.Text = "What is " + randomNumber1 + " % " + randomNumber2 + " ?";
}
private void button5_Click(object sender, EventArgs e)
{
Random random1 = new Random();
int randomNumber1 = random1.Next(6, 11);
Random random2 = new Random();
int randomNumber2 = random2.Next(1, 6);
if (Convert.ToInt16(textBox2.Text) == (randomNumber1) + (randomNumber2))
textBox3.Text = "Correct!";
else if (Convert.ToInt16(textBox2.Text) == (randomNumber1) - (randomNumber2))
textBox3.Text = "Correct!";
else if (Convert.ToInt16(textBox2.Text) == (randomNumber1) * (randomNumber2))
textBox3.Text = "Correct!";
else if (Convert.ToInt16(textBox2.Text) == (randomNumber1) % (randomNumber2))
textBox3.Text = "Correct!";
else
textBox3.Text = "Incorrect!";
}
}
}
and what I'm looking to do is if button 1 is clicked you add, button 2 you subtract, button 3 you multiply, button 4 you mod and then depending on which one was clicked you click submit and it'll tell you whether you got the right answer or not. What I currently have somewhat does that but if the answer is any of the four types of questions answers it'll show it as correct.
ie: the question is 8 + 3 and you put 5, it'll say correct because 8 - 3 is 5
You can try the following code instead, you code has fairly many things redundant and the checking mechanism to determine if user answers correctly is totally wrong:
public enum Operation {
Add,
Subtract,
Divide,
Multiply,
Modulo
}
Random rand = new Random();
private decimal GenerateQuestion(Operation o){
int a = rand.Next(6, 11);
int b = rand.Next(1, 6);
decimal result = 0;
string os = "";
switch(o){
case Operation.Add:
result = a + b;
os = "+";
break;
case Operation.Subtract:
result = a - b;
os = "-";
break;
case Operation.Multiply:
result = a * b;
os = "*";
break;
case Operation.Divide:
result = (decimal)a/b;
os = "/";
break;
case Operation.Modulo:
result = a % b;
os = "%";
break;
}
textBox1.Text = string.Format("What is {0} {1} {2}?", a,os,b);
return result;
}
decimal result;
private void button1_Click(object sender, EventArgs e)
{
result = GenerateQuestion(Operation.Add);
}
private void button2_Click(object sender, EventArgs e){
result = GenerateQuestion(Operation.Subtract);
}
private void button3_Click(object sender, EventArgs e){
result = GenerateQuestion(Operation.Multiply);
}
private void button4_Click(object sender, EventArgs e){
result = GenerateQuestion(Operation.Modulo);
}
private void button5_Click(object sender, EventArgs e){
decimal v;
if(decimal.TryParse(textBox2.Text, out v)){
textBox3.Text = (v == result) ? "Correct!" : "Incorrect!";
}else {
textBox3.Clear();
MessageBox.Show("Enter a number please!");
}
}
You can assign one event handler to multiple buttons, and then check the EventArgs to tell which button fired the event, and put appropriate conditional logic in there.
Not sure if this is ASP.NET or WinForms, but it works something along the lines of:
btn1.Click += button_Click;
btn2.Click += button_Click;
btn3.Click += button_Click;
private void button_Click(object sender, EventArgs e)
{
var btn = sender as Button;
if (sender != null) {
if (btn is btn1) {
//do something
}
else if (btn is btn2) {
//do something
}
//etc
}
}
I have added the event handlers declaratively but you could do this through the properties dialog or in the markup.
I am assuming you are doing a Windows Application here (not Web). In that case, why don't you simply have a class level variable to store the last operation (subtract, add etc), and include check of that variable in the if condition.
eg:
public enum Operations
{
Add,
Subtract
}
private void button1_Click(object sender, EventArgs e)
{
Random random1 = new Random();
int randomNumber1 = random1.Next(6, 11);
Random random2 = new Random();
int randomNumber2 = random2.Next(1, 6);
var currentOperation = Operations.Add
textBox1.Text = "What is " + randomNumber1 + " + " + randomNumber2 + " ?";
}
if (Convert.ToInt16(textBox2.Text) == (randomNumber1) + (randomNumber2) && currentOperation == Operations.Add)
textBox3.Text = "Correct!";
You are generating random (*) numbers to create question and again to validate it. It makes absolutely no sense since you have something like "What is 3 + 4" and you comparing result to 7 + 2 or some other random value.
You should save generated values and operation for verification in some member variable, or even easier simply save expected result.
Random random = new Random();
int expectedResult;
private void button3_Click(object sender, EventArgs e)
{
int randomNumber1 = random.Next(6, 11);
int randomNumber2 = random.Next(1, 6);
textBox1.Text = "What is " + randomNumber1 + " * " + randomNumber2 + " ?";
expectedResult = randomNumber1 * randomNumber2;
}
private void button5_Click(object sender, EventArgs e)
{
textBox3.Text =
int.Parse(textBox2.Text) == expectedResult ? "Correct!" : "Incorrect!";
}
(*) Note that your current "random" numbers are not exactly random due to your code restarting sequence on each call - so pairs of numbers would be very closely related. Note that numbers generated for expression will likely be different from numbers generated for the check. Proper usage is to have one single Random object (potentially one-per-thread, but you don't need to worry about it for your case).
Related
I have a population estimator program for school, the results do not display the first set of results. Here is the code.
private void Button1_Click(object sender, EventArgs e)
{
double startingPop;
double increasePer;
double numDays;
const int INTERVAL = 1;
if (double.TryParse(textBox1.Text, out startingPop))
{
if (double.TryParse(textBox2.Text, out increasePer))
{
if (double.TryParse(textBox3.Text, out numDays))
{
for (int i = 1; i <= numDays; i += INTERVAL)
{
startingPop = (startingPop * (increasePer / 100) + startingPop);
Results.Items.Add("After " + i + " days, the amount of organisms is " + startingPop);
}
}
}
}
}
private void Button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void Button3_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
Results.Items.Clear();
}
I want it to show day 1 2 organisms, instead it shows the first calculation with the increase percentage i.e (day 1 2.6). I know this is probably super obvious so I apologize. Thanks for your insight.
If I understand your problem correctly, your code should look something like this:
private void button1_Click(object sender, EventArgs e)
{
double startingPop;
double increasePer;
double numDays;
const int INTERVAL = 1;
if (double.TryParse(textBox1.Text, out startingPop) &&
double.TryParse(textBox2.Text, out increasePer) &&
double.TryParse(textBox3.Text, out numDays))
{
Results.Items.Add("On the first day, the amount of organisms is " + startingPop);
for (int i = 1; i <= numDays; i += INTERVAL)
{
startingPop = (startingPop * (increasePer / 100) + startingPop);
Results.Items.Add("After " + i + " day(s), the amount of organisms is " + startingPop);
}
}
}
The changes I made to the code:
Combine the three if statements into one using the && operator.
Print the population value before increasing it so that the next displayed value (which reads "after 1 day") will be the next incremented value.
To make your result items grammatically correct, you may the second line inside the loop with something like:
string s = (i > 1 ? "s" : string.Empty);
Results.Items.Add($"After {i} day{s}, the amount of organisms is {startingPop}.");
Now, assuming the values in textBox1, textBox2, textBox3 are 2, 30, and 5, the displayed result would be something like this:
I'm still fairly new to C# programming language. I have to create a simple calculator which can add, subtract, multiply, divide two numbers of users choice without decimals. My Calculator has two input text boxes and one output text box. I've only got 4 operator buttons which are; +,-,*,/. In addition, I also added a 'Backspace' button.
When user inputs the two values, they have to press one of the operator buttons. For example; if the user types in 10 in 'textBox1' and 20 in 'textBox2' and presses 'Button15', the value of the sum will be displayed in 'textBox2'.
There is link of image below the code.
So my problem is with the code under "=" Button15 - I am able to display my user input values but there is problem with my result. I have used my own approach and it might be incorrect.
I would appreciate any help.
Here's the source code:
public partial class Form1 : Form
{
int FirstNumber;
string Operation;
string l;
public Form1()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
if(textBox1.Text=="0")
{
textBox1.Text = "6";
}
else
{
textBox1.Text = textBox1.Text + "6";
}
}
private void button15_Click(object sender, EventArgs e)
{
int SecondNumber;
int Result;
if (Operation == "+")
{
string l = textBox1.Text;
int index = l.IndexOf("+");
string result = l.Substring(index + 1);
SecondNumber = Convert.ToInt16(result);
Result = (FirstNumber + SecondNumber);
textBox2.Text = Convert.ToString(Result);
}
else if (Operation == "-")
{
string l = textBox1.Text;
int index = l.IndexOf("-");
string result = l.Substring(index + 1);
SecondNumber = Convert.ToInt16(result);
Result = (FirstNumber - SecondNumber);
textBox2.Text = Result.ToString();
}
else if (Operation == "x")
{
string l = textBox1.Text;
int index = l.IndexOf("x");
string result = l.Substring(index + 1);
SecondNumber = Convert.ToInt16(result);
Result = (FirstNumber * SecondNumber);
textBox2.Text = Convert.ToString(Result);
}
else if(Operation=="/")
{
string l = textBox1.Text;
int index = l.IndexOf("/");
string result = l.Substring(index + 1);
SecondNumber = Convert.ToInt16(result);
if ( SecondNumber == 0)
{
textBox1.Text = "Cannot divide by 0";
}
else
{
Result = (FirstNumber / SecondNumber);
textBox2.Text = Convert.ToString(Result);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "1";
}
else
{
textBox1.Text = textBox1.Text + "1";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "2";
}
else
{
textBox1.Text = textBox1.Text + "2";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "3";
}
else
{
textBox1.Text = textBox1.Text + "3";
}
}
private void button5_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "5";
}
else
{
textBox1.Text = textBox1.Text + "5";
}
}
private void button6_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "4";
}
else
{
textBox1.Text = textBox1.Text + "4";
}
}
private void button9_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "7";
}
else
{
textBox1.Text = textBox1.Text + "7";
}
}
private void button8_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "8";
}
else
{
textBox1.Text = textBox1.Text + "8";
}
}
private void button7_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "9";
}
else
{
textBox1.Text = textBox1.Text + "9";
}
}
private void button10_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "0";
}
private void button11_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "-";
textBox1.Text = textBox1.Text + Operation;
}
private void button12_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "+";
textBox1.Text = textBox1.Text + Operation;
}
private void button13_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "x";
textBox1.Text = textBox1.Text + Operation;
}
private void button14_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "/";
textBox1.Text = textBox1.Text + Operation;
}
private void Form1_Load(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
textBox1.Text = textBox1.Text + "0";
}
private void button16_Click(object sender, EventArgs e)
{
textBox1.Text = "0";
}
Here is the image of my calculator. The textBox1, the one at the top is happily displaying the user input but the one below, textBox2 is not working when clicked on "="
In your button event handlers you declare new FirstNumber and Operation variables and assign them. These aren't the same as the Form's FirstNumber and Operation. You don't need to declare them again, you can just assign to them.
private void button11_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "-";
textBox1.Text = textBox1.Text + Operation;
}
should be
private void button11_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToInt32(textBox1.Text);
Operation = "-";
textBox1.Text = textBox1.Text + Operation;
}
and similar for the rest of your button clicked event handlers.
First of all, please give dhe controls and event handlers meaningful names. You can change the name in the properties columns in Design View.
Secondly, you declare new variables in the methods for handling operator button clicks.
For example, you have int FirstNumber and string Operation in the event handlers. After the declaration the class variables with the same name are shadowed, and you access only the new variables inside those handlers.
Remove the int and string. The way you have it, you never change the class fields.
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
it's not recognizing my lstSectionNumber (Tickets.TicketForm.lastSectionNumber is inaccessible due to its protection level). Hopefully I explained everything clearly, I'm just recently started learning C#, any help would be appreciated. Thank you in advance.
public class TicketOrder
{
private static int premiumTicket = 40;
private static int basicTicket = 20;
private static int serviceCharge = 2;
private TicketForm form = new TicketForm();
public double CalcTicketCost(int section, double quantity)
{
double amount = 0;
if (int.Parse(form.lstSectionNumber.SelectedItem.Value) <= 150)
{
amount = (quantity*premiumTicket) + (quantity*serviceCharge);
return amount;
}
else
{
amount = (quantity*basicTicket) + (quantity*serviceCharge);
}
return amount;
}
}
Code-behind:
public partial class TicketForm : System.Web.UI.Page
{
int myInt;
public const double premiumTicket = 40;
public const double basicTicket = 20;
public const double serviceCharge = 2;
TicketUser user = new TicketUser();
TicketOrder order = new TicketOrder();
protected void Page_Load(object sender, EventArgs e)
{
// This disables the unobtrusive validation in order to see the result
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
// This will keep my five numbers in my list box without adding more with a refresh of a page
if (!IsPostBack)
{
Random RandomSection = new Random();
for (int i = 0; i < 5; i++)
{
// Created a list box with five random numbers from 1 to 300
myInt = RandomSection.Next(1, 300);
lstSectionNumber.Items.Add(myInt.ToString());
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// I also added TextMode="Number"to my <asp:TextBox ID="txtNumberOfTickets"
// runat="server" Height="18px" Width="134px"></asp:TextBox> code in order
// to get rid of an error incase I left my txtNumberOfTicket empty
int section = Convert.ToInt32(lstSectionNumber.SelectedValue);
double ticketQuantity = Convert.ToInt32(txtNumberOfTickets.Text);
//This label displays users first and last names, number of tickers, seat section number and ticket price
lblPrice.Text = txtFirstName.Text + " " +
txtLastName.Text + ", " +
txtNumberOfTickets.Text + " " +
"Tickets in Section:" + " " +
lstSectionNumber.SelectedValue + "," +
" Total Cost is: " +
order.CalcTicketCost(section, ticketQuantity).ToString("C");
}
protected void btnCreateAccount_Click(object sender, EventArgs e)
{
user.firstName = txtFirstName.Text;
user.lastName = txtLastName.Text;
user.username = txtUserName.Text;
lblCreateAccount.Text = user.CreateAccount();
}
}
Simply give your constructor an empty body
change
public TicketOrder()
to
public TicketOrder() { }
TO solve your other problem, you are trying to make a NEW page, but asp.NET has already made a page for this page load and populated the values for you. You should Pass the current page object into your TicketOrder constructor and save instead.
Like so:
public TicketOrder(TicketForm form)
{
this.form = form;
}
and change in TicketOrder
private TicketForm form = new TicketForm();
to
private TicketForm form;
and change in TicketForm
TicketOrder order = new TicketOrder();
to
TicketOrder order;
public TicketForm()
{
this.order = new TicketOrder(this);
}
Well, I figured it out.
if (section <= 150)
{ amount = (quantity * premiumTicket) + (quantity * serviceCharge);
return amount;
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.