Im currently creating a windows form that must only allow a password through when it matches certain criteria. Im close to finishing however im a bit stuck with one element. "the first and last characters of the password HAVE to be numbers".
looking at my current code how would i go about this because i have ZERO idea. so baby steps and patience would be appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace password_test
{
public partial class Form1 : Form
{
bool Finished = false;
private bool TestPassword(string passwordText, int minimumLength = 5, int maximumLength = 12, int minimumNumbers = 1, int minimumLetters = 1)
{
int letters = 0;
int digits = 0;
int minLetters = 0;
if (passwordText.Length < minimumLength)
{
MessageBox.Show("You must have at least " + minimumLength + " characters in your password.");
return false;
}
if (passwordText.Length > maximumLength)
{
MessageBox.Show("You must have no more than " + maximumLength + " characters in your password.");
return false;
}
foreach (var ch in passwordText)
{
if (char.IsLetter(ch)) letters++;
if (char.IsDigit(ch)) digits++;
if (ch > 96 && ch < 123)
{
minLetters++;
}
}
if (digits < minimumNumbers)
{
MessageBox.Show("You must have at least " + minimumNumbers + " numbers in your password.");
return false;
}
if (minLetters < minimumLetters)
{
MessageBox.Show("You must have at least " + minimumLetters + " letter in your password");
return false;
}
Finished = true;
return true;
}
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void butConfirm_Click(object sender, EventArgs e)
{
if (txtPassword.Text == txtRetypePassword.Text)
{
bool temp = TestPassword(txtPassword.Text, 10, 100, 1, 1);
if (Finished == true)
{
MessageBox.Show("Password Accepted");
Application.Exit();
//this.Hide();
//Form2 f2 = new Form2();
//f2.ShowDialog();
}
}
else
{
MessageBox.Show("Please ensure the passwords you have typed match");
return;
}
}
private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar))
{
e.Handled = true;
}
else
{
return;
}
}
private void txtRetypePassword_TextChanged(object sender, EventArgs e)
{
}
}
}
Before Finished = true; you can simply do your check:
if (!char.IsDigit(passwordText[0]) || !char.IsDigit(passwordText[passwordText.Length - 1]))
{
MessageBox.Show("The first and last characters of the password have to be numbers");
return false;
}
Finished = true;
You should also enforce a minimum length in your method.
Or you can use Regex Test Pattern
// ^\d = start with digit
// \d$ end with digit
// .{3,10} including start and ending, min 5 max 12
if (!Regex.IsMatch(str, #"\d.{3,10}\d$")
{
// Invalid
}
Use \D to reverse.
Related
I am trying to make a form using C# that is similar to a calculator.
I have to code a method named IsOperator that checks that the text box that’s passed to it contains a value of +, -, *, or /.
For some reason it is not validating correctly.
I've tried changing the || to && and reversing the returns to false and true but nothing works.
When I try putting other things in the operator text box that are not + / - * the results turn into 0. Nothing ends up validating.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimpleCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
try
{
if (IsValidData())
{
MessageBox.Show("Error");
}
else
{
decimal operand1 = Convert.ToDecimal(txtOperand1.Text);
string operator1 = txtOperator.Text;
decimal operand2 = Convert.ToDecimal(txtOperand2.Text);
decimal result = 0;
if (operator1 == "+")
result = operand1 + operand2;
else if (operator1 == "-")
result = operand1 - operand2;
else if (operator1 == "*")
result = operand1 * operand2;
else if (operator1 == "/")
result = operand1 / operand2;
result = Math.Round(result, 4);
txtResult.Text = result.ToString();
txtOperand1.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" +
ex.GetType().ToString() + "\n" +
ex.StackTrace, "Exception");
}
}
public bool IsValidData()
{
return
//validate the operand1 text box
IsPresent(txtOperand1, "Operand 1") &&
IsDecimal(txtOperand1, "Operand 1") &&
IsWithinRange(txtOperand1, "Operand 1", 0, 1000000) &&
//validates the operator text box
IsPresent(txtOperator, "Operator") &&
IsOperator(txtOperator, "Operator") &&
//validates the operand 2 text box
IsPresent(txtOperand2, "Operand 2") &&
IsDecimal(txtOperand2, "Operand 2") &&
IsWithinRange(txtOperand2, "Operand 2", 0, 1000000);
}
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
//is present
public bool IsPresent(TextBox textBox, string name)
{
if (textBox.Text == "")
{
MessageBox.Show(name + " is a required field.", "Entry Error");
textBox.Focus();
}
return false;
}
//is decimal
public bool IsDecimal(TextBox textBox, string name)
{
decimal number = 0m;
if (Decimal.TryParse(textBox.Text, out number))
{
return true;
}
else
{
MessageBox.Show(name + " must be a decimal value.", "Entry Error");
textBox.Focus();
return false;
}
}
//is within range
public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max)
{
decimal number = Convert.ToDecimal(textBox.Text);
if (number < min || number > max)
{
MessageBox.Show(name + "must be between" + min.ToString()
+ "and" + max.ToString() + ".", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
//is a valid operator
public bool IsOperator(TextBox textBox, string name)
{
string operator1 = "";
operator1 = Convert.ToString(textBox.Text);
if (operator1 == "+" && operator1 == "-" && operator1 == "/" && operator1 == "*")
{
MessageBox.Show("Please enter a valid operator in the operator text box.", "Entry Error");
return false;
}
return true;
}
private void txtOperand1_TextChanged(object sender, EventArgs e)
{
this.txtResult.Text = "";
}
private void txtOperator_TextChanged(object sender, EventArgs e)
{
this.txtResult.Text = "";
}
private void txtOperand2_TextChanged(object sender, EventArgs e)
{
this.txtResult.Text = "";
}
}
}
Fist of all you should not use someString == "" instead use string.IsNullOrEmpty(someString) or string.IsEmptyOrWhitespace(someString). 1
Then IsPresent always returns false. You may change that method to
public bool IsPresent(TextBox textBox, string name)
{
if (!string.IsNullOrEmpty(textBox.Text))
{
return true;
}
MessageBox.Show(name + " is a required field.", "Entry Error");
textBox.Focus();
return false;
}
In the EventHandler your forgot a ! before IsValidData(). You you're showing an Error, when the data is valid and try to perform the calculation, when your data is faulty.
Your IsOperator Method contains in fact a logical issue. You want to return true, if the operator is any of the following chars +, -, *, \. So its easier to flip the if logic to something like this using LINQ
//is a valid operator
public bool IsOperator(TextBox textBox, string name)
{
string operator = textBox.Text;
if (new[] {"+", "-", "*", "/"}.Contains(operator))
{
return true;
}
MessageBox.Show("Please enter a valid operator in the operator text box.", "Entry Error");
return false;
}
I think your code also could benefit from using Exceptions instead of showing MessageBoxes as soon an error occurs.
This question already has answers here:
How do I make a textbox that only accepts numbers?
(41 answers)
Closed 5 years ago.
I created a guessing game application. When the user enters a letter it crashes. I want the textbox to only have integers. I was trying to create a validation so when the user enters a letter it will display a message only integers only. How can I add a validation to the program so where the user can only enter an integer?
I tried using this code but it still crashes:
double input = Convert.ToInt32(txtInput.Text);
if (Double.TryParse(txtInput.Text, out input))
{
txtInput.Text = Convert.ToString(input);
}
else
{
MessageBox.Show("Please enter a valid number.");
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double guess;
private void Form1_Load(object sender, EventArgs e)
{
Random rand = new Random();
guess = rand.Next(1, 101);
}
private void Clickbutton_click(object sender, EventArgs e)
{
double input = Convert.ToInt32(txtInput.Text);
if (Double.TryParse(txtInput.Text, out input))
{
txtInput.Text = Convert.ToString(input);
}
else
{
MessageBox.Show("Please enter a valid number.");
}
if (input == guess)
{
lblMessage.Text = "You Are Corrrect, You Win" + " " +
" \r\n Random Number was = " + Convert.ToString(guess);
}
else if (input > guess)
{
lblMessage.Text = "Number is too High, Try Again";
txtInput.Clear();
}
else if (input < guess)
{
lblMessage.Text = "Number is too Low, Try Again";
txtInput.Clear();
}
}
}
}
You can use the NumericUpDown control.
The advantage of this control, is that it does not only has a text box, but also only numbers can be entered, and there are two small buttons on the right to increase with 1 or decrease with 1 (at least by default).
Also, more properties can be set.
The official documentation can be found here
And below is an example how it looks:
At codeproject an extended version can be found.
Besides the answer with the NumericUpDown.
Just something to add. With some little adjustments your code will work.
private void Clickbutton_click(object sender, EventArgs e)
{
//// Convert.ToInt32 throws an exception if it fails
//// to parse the string to an integer
//// So you don't want to parse the input directly
////double input = Convert.ToInt32(txtInput.Text);
// Your second attempt is the goal
double input;
if (!Double.TryParse(txtInput.Text, out input))
{
MessageBox.Show("Please enter a valid number.");
return; //// We are done. Nothing more to do here
}
txtInput.Text = input.ToString();
if ( input == guess)
{
lblMessage.Text = "You Are Corrrect, You Win" + " "+
" \r\n Random Number was = " + Convert.ToString(guess);
}
else if (input > guess)
{
lblMessage.Text = "Number is too High, Try Again";
txtInput.Clear();
}
else if (input < guess)
{
lblMessage.Text = "Number is too Low, Try Again";
txtInput.Clear();
}
}
I'm not sure if I'm writing the call correctly. 'intQty' says doesn't exist in current context. So how would I go about fixing that?
txtQty.Text = getPrice(intQty);
txtPrice.Text = decPrice.ToString("C2");
//Also to compute the order total it has to be written as
Order Total = (Order Qty * Price) * (1 + Tax Rate)
what I have: decTotal = (intQty * decPrice) * (1 + fltTaxRate);
so would I replace the that with values I've already declared?
EDIT: 'intQty' is declared right under the btnCalculate_Click as 'int intQty;'
there's data validation underneath and some methods as well.
FULL CODE:
string sCboStates;
int intQty;
string sWrapperSample;
// data validation
try
{
intQty = Convert.ToInt32(txtQty.Text);
}
catch
{
MessageBox.Show("Contents are not numeric.",
"Quantity",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtQty.Focus();
return;
}
try
{
sWrapperSample = Convert.ToString(txtWrapperSample.Text);
}
catch
{
MessageBox.Show("Content's empty.",
"Wrapper Sample",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtLine1.Focus();
return;
}
try
{
sCboStates = Convert.ToString(cboStates.Text);
}
catch
{
MessageBox.Show("Content's empty.",
"States",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
cboStates.Focus();
return;
}
}
// Method 1
private decimal getPrice(int intQty)
{
decimal decPrice;
if (intQty <= 500)
{
decPrice = 1.25m;
}
else if (intQty >= 501 && intQty <= 1000)
{
decPrice = 1.05m;
}
else if (intQty >= 1001 && intQty <= 5000)
{
decPrice = .90m;
}
else if (intQty > 5001)
{
decPrice = .75m;
}
decPrice = Convert.ToDecimal(txtPrice.Text);
txtQty.Text = intQty.ToString();
return intQty;
}
//Method 2
private float getTaxRate(string sCboStates)
{
string sStates = "";
float fltTaxRate=0;
if (sStates == "CT")
{
fltTaxRate = 0.06f;
}
else if (sStates == "MA")
{
fltTaxRate =.0625f;
}
else if (sStates == "ME")
{
fltTaxRate = .085f;
}
else if (sStates == "NH")
{
fltTaxRate = .0f;
}
else if (sStates == "RI")
{
fltTaxRate = .07f;
}
else if (sStates == "VT")
{
fltTaxRate = .06f;
}
return fltTaxRate;
}
//Method 3
private void formatWrapperSample()
{
txtWrapperSample.Text = txtLine1.Text + " " +
Environment.NewLine +
txtLine2.Text + " " +
Environment.NewLine +
txtLine3.Text;
}
// Method 4
private Color GetColor(string sColorIn)
{
return Color.FromName(sColorIn);
//CALCULATIONS
decimal decTotal = 0;
//Call the price method by passing the numeric value and the text qty
txtQty.Text = getPrice(intQty);
txtPrice.Text = decPrice.ToString("C2");
// Compute the total
decTotal = (intQty * decPrice) * (1 + fltTaxRate);
txtTotal.Text = decTotal.ToString("C2");
}
private void cboWrapperColor_SelectedIndexChanged(object sender, EventArgs e)
{
//Label Color 'cboWrapperColor_Selected' is a typo
txtWrapperSample.BackColor = GetColor(cboLabelColor.Text);
}
private void cboFontColor_SelectedIndexChanged(object sender, EventArgs e)
{
txtWrapperSample.ForeColor = GetColor(cboFontColor.Text);
}
private void cboStates_SelectedIndexChanged(object sender, EventArgs e)
{
getTaxRate("P2");
}
private void btnClear_Click(object sender, EventArgs e)
{
txtLine1.Clear();
txtLine2.Clear();
txtLine3.Clear();
txtQty.Clear();
txtWrapperSample.Clear();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
It looks like there is some code missing, is everything starting with //CALCULATIONS to the end of the code part of the GetColor() method?
At any rate, you're declaring and initializing intQty in your btnCalculate_Click event handler. This means that the rest of your program does not know about intQty (with the exception of GetPrice() since you're passing it in).
Declare intQty as a global variable at the top of your class and then set the correct value in btnCalculate_Click
That way when you go to do the calculations it will know about intQty
Also...
You are using exceptions to control program flow, which is generally considered bad practice.
Exceptions are for exceptional cases, because they are computationally expensive.
You should use Int32.TryParse() instead
txtQty.Text = getPrice(intQty);
For one your method returns Decimal - you can't assign it to String property. C# is stringly typed.
When I hit the 'calculate' button, the 'additional programs' and 'installations' textboxes revert back to 0 and the 'bill' comes out to the base price for the given customer type. My code is below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bus432_Assignment2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
const double RES_HOME = 99;
const double RES_HOME_ADD = 49;
const double ENT_ADD_PRO = 10;
const double ENT_BASIC = 249;
const double ENT_PER_PRO = 99;
const double ENT_ADD_INSTALL_CHARGE = .10;
const double UNLIM_BASIC = 999;
char customerType;
double addpro = 0;
double install = 0;
double bill = 0;
// Check to make sure type has been entered.
if (txtCustomerType.Text == "")
{
MessageBox.Show("Customer type is required.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCustomerType.Focus();
return;
}
// Get customer type
customerType = char.Parse(txtCustomerType.Text);
customerType = char.ToUpper(customerType);
txtCustomerType.Text = customerType.ToString();
// Check customer type, programs, installations
txtInstall.Text = install.ToString();
txtAddPro.Text = addpro.ToString();
if (customerType == 'H' || customerType == 'E')
{
if (txtInstall.Text == "")
{
MessageBox.Show("For home use customer plan, enter installations",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
if (txtInstall.Text == "")
{
txtInstall.Focus();
}
return;
}
}
else if (customerType == 'E' || customerType == 'H')
{
if (txtAddPro.Text == "")
{
MessageBox.Show("For enterprise or home use customer, enter additional programs",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
if (txtAddPro.Text == "")
{
txtAddPro.Focus();
}
return;
}
else if (customerType != 'E' || customerType != 'H' || customerType != 'U')
{
MessageBox.Show("Customer type must be E, H, or U.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
//txtInstall.Focus();
return;
}
// Get Additional Programs and installations
addpro = double.Parse(txtAddPro.Text);
install = double.Parse(txtInstall.Text);
if (addpro < 0)
{
MessageBox.Show("Number of additional programs must not be negative.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
txtAddPro.Focus();
return;
}
else if (install < 0 )
{
MessageBox.Show("Number of installations must not be negative.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
txtInstall.Focus();
return;
}
}
// Calculate Bill
switch(customerType)
{
case 'H':
bill = RES_HOME + addpro * RES_HOME_ADD;
break;
case 'E':
bill = ENT_BASIC + addpro * ENT_PER_PRO *(1+ENT_ADD_INSTALL_CHARGE*(install-ENT_ADD_PRO));
break;
case 'U':
bill = UNLIM_BASIC;
break;
}
// Display the result.
txtBill.Text = bill.ToString("C");
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
}
}
Within the code, you have declared these two variables
double addpro = 0;
double install = 0;
Then after you have declared these, you are setting the text of the boxes to equal them, without ever setting their values to anything but 0.
txtInstall.Text = install.ToString();
txtAddPro.Text = addpro.ToString();
I am not too sure on what you are trying to achieve, so I cannot suggest what you should have there instead, however that is the source of your problems regarding displaying 0 within the text fields.
if (getchar == '+') {
answer = getnum1+getnum2; // if the random operation is add, it will add
addtemp++; // <---- disregard this
if (answer == getanswer) // the answer from my textbox which is
{ // user-input it is stored on "getanswer"
correct++; // it is compared if its correct or wrong
addcomp++;
}
else { wrong++; }
}
else if (getchar == '-') {
subtemp++;
answer = nextValue - nextValue1;
if (answer == getanswer) {
correct++;
subcomp++;
}
else { wrong++; }
}
else if (getchar == '*') {
multemp++;
answer = nextValue * nextValue1;
if (answer == getanswer) {
correct++;
mulcomp++;
}
else { wrong++; }
}
else if (getchar == '/') {
divtemp++;
answer = nextValue / nextValue1;
if (answer == getanswer) {
correct++;
divcomp++;
}
else { wrong++; }
}
else if (getchar == '%') {
modtemp++;
answer = nextValue % nextValue1;
if (answer == getanswer) {
correct++;
modcomp++;
}
else { wrong++; }
}
C# programming HELP! Now whenever i press the button "SCORES" it is a MessageBox.Show(correct or wrong) , the values are wrong. it sometimes increment corrected but just once or twice.Is there something wrong with my code?
///////////////////////////////////////////////////////////
ENTIRE CODE for #boncodigo
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace A1_ALS_Noroña
{
public partial class Form1 : Form
{
int minV=0, maxV=0,ques=0,tempques=1;
int addtemp, subtemp, multemp, divtemp, modtemp;
int addcomp, subcomp, mulcomp, divcomp, modcomp;
int answer,getanswer;
int getnum1, getnum2;
char getchar;
char[] select = new char[5];
int count=0;
int correct, wrong;
public Form1()
{
InitializeComponent();
}
private void bttnstart_Click(object sender, EventArgs e)
{
bttnanswer.Enabled = true;
grpbox1.Enabled = false;
bttnanswer.Enabled = true;
lblnum1.Visible = true;
lblnum2.Visible = true;
lbloperator.Visible = true;
bttnstop.Enabled = true;
bttnscore.Enabled = true;
bttnstart.Enabled = false;
Random random = new Random();
int nextValue = random.Next(minV, maxV);
int nextValue1 = random.Next(minV, maxV);
lblnum1.Text = nextValue.ToString();
lblnum2.Text = nextValue1.ToString();
var rand = new Random();
char num = select[rand.Next(count)];
lbloperator.Text = Convert.ToString(num);
}
private void txtboxmin_TextChanged(object sender, EventArgs e)
{
minV = Convert.ToInt32(txtboxmin.Text);
}
private void txtbxmax_TextChanged(object sender, EventArgs e)
{
maxV = Convert.ToInt32(txtbxmax.Text);
}
private void bttnexit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void bttnstop_Click(object sender, EventArgs e)
{
MessageBox.Show("APPLICATION STOP! The application will restart.");
Application.Restart();
}
private void bttnanswer_Click(object sender, EventArgs e)
{
tempques++;
Random random = new Random();
int nextValue = random.Next(minV,maxV);
int nextValue1 = random.Next(minV, maxV);
lblnum1.Text = nextValue.ToString();
var rand = new Random();
char num = select[rand.Next(count)];
lbloperator.Text = Convert.ToString(num);
lblnum2.Text = nextValue1.ToString();
getnum1 = Convert.ToInt32(lblnum1.Text);
getnum2 = Convert.ToInt32(lblnum2.Text);
getanswer = Convert.ToInt32(txtbxans.Text);
getchar = Convert.ToChar(lbloperator.Text);
if (getchar == '+')
{
answer = getnum1 + getnum2;
addtemp++;
if (answer == getanswer)
{
correct++;
addcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '-')
{
subtemp++;
answer = nextValue - nextValue1;
if (answer == getanswer)
{
correct++;
subcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '*')
{
multemp++;
answer = nextValue * nextValue1;
if (answer == getanswer)
{
correct++;
mulcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '/')
{
divtemp++;
answer = nextValue / nextValue1;
if (answer == getanswer)
{
correct++;
divcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '%')
{
modtemp++;
answer = nextValue % nextValue1;
if (answer == getanswer)
{
correct++;
modcomp++;
}
else
{
wrong++;
}
}
}
private void txtbxques_TextChanged(object sender, EventArgs e)
{
ques = Convert.ToInt32(txtbxques.Text);
}
private void chkbxtimer_CheckedChanged(object sender, EventArgs e)
{
rdoeasy.Enabled = true;
rdomed.Enabled = true;
rdohard.Enabled = true;
}
private void chkboxAdd_CheckedChanged(object sender, EventArgs e)
{
if (chkboxAdd.Checked == true)
{
select[count] = '+';
count++;
}
else if (chkboxAdd.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxSub_CheckedChanged(object sender, EventArgs e)
{
if (chkboxSub.Checked == true)
{
select[count] = '-';
count++;
}
else if (chkboxSub.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxMul_CheckedChanged(object sender, EventArgs e)
{
if (chkboxMul.Checked == true)
{
select[count] = '*';
count++;
}
else if (chkboxMul.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxDiv_CheckedChanged(object sender, EventArgs e)
{
if (chkboxDiv.Checked == true)
{
select[count] = '/';
count++;
}
else if (chkboxDiv.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxMod_CheckedChanged(object sender, EventArgs e)
{
if (chkboxMod.Checked == true)
{
select[count] = '%';
count++;
}
else if (chkboxMod.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void bttnscore_Click(object sender, EventArgs e)
{
MessageBox.Show("Correct Answer"+correct);
}
}
}
One thing in advance: I don't know where your bug is. Here's just a couple of tips that I think it would make sense if you think about them, in order to avoid similar bugs in the future:
If I had to review this code, my major issue would be with the amount of repeating code, where very similar multi-line long patterns are copied over and over. I think in the whole code you don't call any method, but implement stuff right away in the event-handlers, thereby repeating yourself and multiplying the potential for bugs. Let's look at this code:
if (chkboxSub.Checked == true)
{
select[count] = '-';
count++;
}
else if (chkboxSub.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
apart from the bug with count when you have added several operators to the select-array, this code repeats several times. Let's extract the code into a method and make the bits that change parameterizable:
void AddOrRemoveOperator(bool isChecked, char operatorChar) {
if (isChecked) {
select[count] = operatorChar;
count++;
}
else {
Array.Clear(select, 0, select.Length);
count--;
}
}
Now you can call that method many times, e.g. like:
AddOrRemoveOperator(chkboxSub.Checked, '-');
Next point would be lack of .NET Base Class Library knowledge (BCL). E.g., wouldn't it be easier to use a List<T> instead of an array?
The above method becomes:
void AddOrRemoveOperator(bool isChecked, char operatorChar) {
if (isChecked) {
select.Add(operatorChar);
}
else {
select.Clear();
}
}
An Observation: All operators except the add one use the values nextValue, nextValue1 while the add one uses getnum1 and 2. Is that intended?
Short of extracting the code blocks in bttnanswer_Click into their own class, you can also extract the repeating code into a method:
void PerformComparison(Func<int> answerProvider,
ref int operatorCount,
ref int operatorSpecificCorrectCount)
{
var answer = answerProvider();
operatorCount++;
if (answer == getanswer) {
correct++;
operatorSpecificCorrectCount++;
}
else {
wrong++;
}
}
That code would still drive me mad (because the class you have programmed lacks cohesion), but we have fought code duplication. Now you can call the method e.g. like that:
if (getchar == '+')
{
PerformComparison(()=>getnum1 + getnum2, ref addtemp, ref addcomp);
}
There are many techniques to morph code into forms that are more easily testable and maintainable (refactoring), we have only used extract method so far. For more techniques the book Refactoring: Improving the Design of Existing Code is still highly recommendable.
It might be a float precision issue (maybe your user is entering 3 and the program calculates 2.9999999). Debug your code and identify one case when it is not adding correctly.