C# Hangman Game Error - c#

I keep having this error.
ArgumentOutOfRangeException was unhandled.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Below is the complete code of the form that has the problem and it is where the Hangman game takes place.
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;
using System.Data.SqlClient;
namespace Hangman_APPD_Assignment
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
The List labels = new List(); is the label that the makeLabels() method is going to use it.
String w = "";
List<Label> labels = new List<Label>();
int score = 0, missed = 0, correctCount = 0, gameCount = 1;
The code below is when the user clicks the QUIT button, the application will close.
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
The code below is when the form loads or shows up, the makeLabels() method is used.
private void Form2_Load(object sender, EventArgs e)
{
makeLabels();
}
The code below is to use the random word and convert in to a string replacing each alphabet with a symbol '_'. The converted string will be put inside a label called Labels.
private void makeLabels()
{
w = getRandomWord().ToLower();
w.Replace(" ", "");
char[] letters = w.ToCharArray();
int space = 569 / letters.Length - 1;
for (int i = 0; i < letters.Length; i++)
{
labels.Add(new Label());
labels[i].Location = new Point((i * space) + 10, 109);
labels[i].Parent = groupBox2;
labels[i].Text = "_" + i;
labels[i].BringToFront();
labels[i].CreateControl();
}
lblLength.Text = letters.Length.ToString();
}
The code below is a method to create a new game when 1) the user guesses the word completely or 2) the user runs out of guesses.
private void newGame()
{
gameCount++;
if (gameCount == 15)
{
this.Hide();
if (score >= 7)
{
Form4 f4 = new Form4();
f4.ShowDialog();
}
else
{
Form6 f6 = new Form6();
f6.ShowDialog();
}
}
else
{
getRandomWord();
makeLabels();
enableLetterButtons();
lblMissed.Text = "";
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part0;
}
}
The code below gets a random word from the string array to be used as the mystery word in the game.
public string getRandomWord()
{
Random randomNum = new Random();
String[] words = {"virus", "network", "syntax", "router", "switch", "worms", "trojan", "email", "bios",
"cmos", "ram", "cipher", "malware", "botnet", "cookies", "patches", "cryptograph",
"metamorphic", "polymorphic", "rootkit", "logicbomb", "spam", "spyware", "keyloggers",
"adware", "software", "hardware", "botherder", "phishing", "whaling", "pharming",
"vishing", "spim", "topology", "tailgating", "loop", "java", "motherboard", "unique",
"parameter"};
int randomNumber = randomNum.Next(0, (words.Length - 1));
return words[randomNumber];
}
The code below is to change the picture every time the user guesses wrongly.
private void setPicture(int wrongTry)
{
switch(wrongTry)
{
case 0:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part0;
break;
case 1:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part1;
break;
case 2:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part2;
break;
case 3:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part3;
break;
case 4:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part4;
break;
case 5:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part5;
break;
case 6:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part6;
break;
}
}
The code below is to call a method when the user clicks one of the alphabet buttons.
private void checkGuessedLetter(string wordToGuess, string guessedLetter, Button buttonName)
{
int strLength = wordToGuess.Length;
char letter = guessedLetter.ToCharArray()[0];
buttonName.Enabled = false;
if (w.Contains(guessedLetter))
{
char[] LS = w.ToCharArray();
for (int i = 0; i < LS.Length; i++)
{
if (LS[i] == letter)
{
MessageBox.Show("The value of w is " + w + " AND " + i);
labels[i].Text = letter.ToString();
conditionPic.Image = Hangman_APPD_Assignment.Properties.Resources.correctpic;
correctCount++;
MessageBox.Show("You got correct " + correctCount + " time(s).");
if (correctCount == strLength)
{
MessageBox.Show("Good job! Keep it up, matey!", "Victory!", MessageBoxButtons.OK, MessageBoxIcon.None);
score++;
lblScore.Text = score.ToString();
newGame();
missed = 0;
correctCount = 0;
labels.Clear();
}
}
foreach (Label l in labels)
if (l.Text == "__") return;
}
}
else
{
conditionPic.Image = Hangman_APPD_Assignment.Properties.Resources.wrong;
lblMissed.Text += " " + letter.ToString() + " |";
missed++;
MessageBox.Show("You missed " + missed + " time(s).");
setPicture(missed);
if (missed == 6)
{
MessageBox.Show("Unfortunately, you lost this round... Make sure you won't let this happen again, "
+ "or else you will end up in Davy Jones' Locker.", "Defeat!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
newGame();
missed = 0;
correctCount = 0;
labels.Clear();
}
}
}
The code below is to get the score that is accumulated at the lblScore label to be shown in the next form.
public int getScore()
{
int score = int.Parse(lblScore.Text);
return score;
}
The codes below is to call a method when the user clicks a button that contains an alphabet to guess the word in the Hangman game.
private void Abtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "a", Abtn);
}
private void Bbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "b", Bbtn);
}
private void Cbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "c", Cbtn);
}
private void Dbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "d", Dbtn);
}
private void Ebtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "e", Ebtn);
}
private void Fbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "f", Fbtn);
}
private void Gbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "g", Gbtn);
}
private void Hbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "h", Hbtn);
}
private void Ibtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "i", Ibtn);
}
private void Jbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "j", Jbtn);
}
private void Kbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "k", Kbtn);
}
private void Lbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "l", Lbtn);
}
private void Mbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "m", Mbtn);
}
private void Nbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "n", Nbtn);
}
private void Obtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "o", Obtn);
}
private void Pbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "p", Pbtn);
}
private void Qbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "q", Qbtn);
}
private void Rbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "r", Rbtn);
}
private void Sbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "s", Sbtn);
}
private void Tbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "t", Tbtn);
}
private void Ubtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "u", Ubtn);
}
private void Vbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "v", Vbtn);
}
private void Wbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "w", Wbtn);
}
private void Xbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "x", Xbtn);
}
private void Ybtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "y", Ybtn);
}
private void Zbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "z", Zbtn);
}
The code below is to enable back all the buttons that has been clicked on the previous game.
private void enableLetterButtons()
{
Abtn.Enabled = true;
Bbtn.Enabled = true;
Cbtn.Enabled = true;
Dbtn.Enabled = true;
Ebtn.Enabled = true;
Fbtn.Enabled = true;
Gbtn.Enabled = true;
Hbtn.Enabled = true;
Ibtn.Enabled = true;
Jbtn.Enabled = true;
Kbtn.Enabled = true;
Lbtn.Enabled = true;
Mbtn.Enabled = true;
Nbtn.Enabled = true;
Obtn.Enabled = true;
Pbtn.Enabled = true;
Qbtn.Enabled = true;
Rbtn.Enabled = true;
Sbtn.Enabled = true;
Tbtn.Enabled = true;
Ubtn.Enabled = true;
Vbtn.Enabled = true;
Wbtn.Enabled = true;
Xbtn.Enabled = true;
Ybtn.Enabled = true;
Zbtn.Enabled = true;
}
The code below is to close the application when the user clicked the X button on the top right-hand corner of the application.
private void btnOut_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
P.S. I'm sorry I forgot to put in where the error comes from.
So the error is at the
labels[i].Text = letter.ToString();
in the checkGuessedLetter(string wordToGuess, string guessedLetter, Button buttonName) method.

The problem is in these lines:
newGame();
missed = 0;
correctCount = 0;
labels.Clear();
The key thing is to stop and think about what newGame does and then think about what you do afterwards? Since this is homework (I assume from some of the names) really go and think about it.
Done? Good. So hopefully you realised that your newGame method calls MakeLabels to generate the labels and that you then a couple of lines later clear out labels. This means that for subsequent games your labels list will always be empty.
The correct fix for this is that the last three lines I quoted are all part of creating a new game so should be in that method. And indeed you only need to clear the labels when you make new ones so make that part of that method too. Do this and your program will be clearer and hopefully work too! :)

Related

c#: Using enter for KeyDown does not work

I am playing with a basic calculator windows app and trying to make it calculate the equation when pressing the enter key. Currently, if I give it 2+2 and click my equal button it registers 4, as it should. I would like to get the same response when I hit the enter key on the keyboard. I am attempting to do this with this code:
if (e.KeyCode == Keys.Enter)
{
equal.PerformClick();
}
the result is 2+22(last number entered is duplicated)
However, if I use a letter or F-key(as in the below code) it returns the correct answer:
if (e.KeyCode == Keys.C)
{
equal.PerformClick();
}
For reference the following is the code that "equal.PerformClick()" is calling
decimal numA;
decimal numB;
decimal result = 0;
//-------------------------------------------------------------
decimal.TryParse(this.first_num_label.Text, out numA);
decimal.TryParse(this.label1.Text, out numB);
if (this.operator_name.Text == "+")
{
result = numA + numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "-")
{
result = numA - numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "x")
{
result = numA * numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "/")
{
result = numA / numB;
}
//---------------------------------------------------------------
this.label1.Text = result.ToString();
this.first_num_label.Text = "";
this.operator_name.Text = "";
here is the entire code:.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calc_project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void clear_Click(object sender, EventArgs e)
{
//this.label1.Text = "";
this.label1.ResetText();
}
private void one_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "1";
}
private void two_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "2";
}
private void three_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "3";
}
private void four_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "4";
}
private void five_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "5";
}
private void six_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "6";
}
private void seven_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "7";
}
private void eight_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "8";
}
private void nine_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "9";
}
private void zero_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "0";
}
private void plus_Click(object sender, EventArgs e)
{
this.operator_name.Text = "+";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void minus_Click(object sender, EventArgs e)
{
this.operator_name.Text = "-";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void multiply_Click(object sender, EventArgs e)
{
this.operator_name.Text = "x";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void div_Click(object sender, EventArgs e)
{
this.operator_name.Text = "/";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void equal_Click(object sender, EventArgs e)
{
decimal numA;
decimal numB;
decimal result = 0;
//-------------------------------------------------------------
decimal.TryParse(this.first_num_label.Text, out numA);
decimal.TryParse(this.label1.Text, out numB);
if (this.operator_name.Text == "+")
{
result = numA + numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "-")
{
result = numA - numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "x")
{
result = numA * numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "/")
{
result = numA / numB;
}
//---------------------------------------------------------------
this.label1.Text = result.ToString();
this.first_num_label.Text = "";
this.operator_name.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
this.label1.ResetText();
this.first_num_label.ResetText();
this.operator_name.ResetText();
}
private void Decimal_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + ".";
}
private void button2_Click(object sender, EventArgs e)
{
decimal len;
decimal wit;
decimal area;
decimal.TryParse(this.textBox1.Text, out len);
decimal.TryParse(this.textBox2.Text, out wit);
area = len * wit;
if (ft.Checked == true)
{
this.label2.Text = area.ToString() +" square feet";
}
if (meters.Checked == true)
{
this.label2.Text = area.ToString() +" square meters";
}
if (cm.Checked == true)
{
this.label2.Text = area.ToString() + " square centimeters";
}
if (yards.Checked == true)
{
this.label2.Text = area.ToString() + " square yards";
}
//else
//{
// this.label2.Text = area.ToString();
//}
}
private void button3_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
this.textBox2.Text = "";
this.label2.ResetText();
}
private void button4_Click(object sender, EventArgs e)
{
decimal ar;
decimal cov;
decimal req;
//--------------------------------------------
decimal.TryParse(this.textBox4.Text, out ar);
decimal.TryParse(this.textBox3.Text, out cov);
//--------------------------------------------
req = ar / cov;
this.requirement.Text = req.ToString() + " Gallons";
}
private void button5_Click(object sender, EventArgs e)
{
decimal Slabar;
decimal Slabtk;
decimal TKft;
decimal cubFt;
decimal ConYard;
//--------------------------------------------
decimal.TryParse(this.textBox5.Text, out Slabar);
decimal.TryParse(this.textBox6.Text, out Slabtk);
//--------------------------------------------
TKft = Slabtk / 12;
cubFt = Slabar * TKft;
ConYard = cubFt / 27;
//--------------------------------------------
this.label10.Text = ConYard.ToString();
}
private void tabControl1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
equal.PerformClick();
}
if (e.KeyCode == Keys.F1) //this code works
{
MessageBox.Show("test");
}
if (e.KeyCode == Keys.Escape) //so does this
{
this.Close();
}
if (e.KeyCode == Keys.NumPad9) // also works
{
this.label1.Text = this.label1.Text + "9";
}
if (e.KeyCode == Keys.F2)
{
equal.PerformClick();
}
}
}
}
Based on my test, your code works well. If you still have problems, I suggest you can use Form_KeyDown event.
Here is a code example you can refer to.
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
equal.PerformClick();
}
}
I fixed the control focus to textbox1 to prevent the Enter key from being affected by the input number.
After each number is entered, please set textBox1.Focus(). method.
As shown below:
private void one_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "1";
textBox1.Focus();
}
private void two_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "2";
textBox1.Focus();
}
......
......
Finally, it is best for you to check if the enter key is normal.
I'm assuming you are listening on the KeyPress event? If so, have you tried casting the Keys.Enter value to a char?
private void element_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
// Do stuff here
}
}
Keys.Enter and Keys.Return return the same value, so it doesn't matter which one you choose.

I am writing a c# windows form code

I am writing a c# windows form code to
get the number from button1 and button2 and add them together in a text box but The compiler argues on the convert.toint32(textbox3.text) statement
and also it increases the value of the two variable and three variable how can I keep it constant but increase the value of textbox
and I need a solution?
int Three = 0;
int Two = 0;
//int one = 0;
int sum = 0;
// int sum = 0;
//int dec = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Enter the teams` name");
}
private void button1_Click(object sender, EventArgs e)
{
//Three += 3;
//textBox3.Text = sum.ToString();
Three += 3;
sum = Convert.ToInt32(textBox3.Text) + Three;
textBox3.Text = sum.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
Two += 2;
sum = Two + Convert.ToInt32(textBox3.Text) + Three;
textBox3.Text =Convert.ToInt32(textBox3.Text) + Two.ToString();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox3.Text = 0.ToString();
}
`
Change
sum = Convert.ToInt32(textBox3.Text) + Three;
To
sum = Convert.ToInt32(textBox3.Text == "" ? "0" : textBox3.Text) + 3;
Also, remove
private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox3.Text = 0.ToString(); // this
}
because it doesn't make any sense.
Your variables belong to class and they are accessible for initialization in constructor. This can be done in many ways but you need to check if textboxes have values then try to convert it and add it.
private int Two;
private int Three;
private int sum;
public Form1()
{
this.Two = 0;
this.Three = 0;
this.sum = 0;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Enter the teams` name");
}
private void button1_Click(object sender, EventArgs e)
{
this.Three += 3;
sum = textBox3.Text != String.Empty ? Convert.ToInt32(textBox3.Text) : 0;
textBox3.Text = Convert.ToString(sum + this.Three);
}
... same for number Two
private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox3.Text = "0";
}

Wait and do something on few websites in C#

I want full load 3 websites with one browser (not in same time) and do some tasks.
My code;
string[] websites =
{
"www.facebook.com", "www.bug.hr", "www.htmlgoodies.com"
};
string[] inputs =
{
"first", "second", "third"
};
private void Form1_Load(object sender, EventArgs e)
{
Browser1.Navigate(websites[0]);
}
private void Browser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (Browser1.Url.ToString().Contains(websites[0]))
{
while (Browser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
Browser1.Document.GetElementById("email").SetAttribute("value", inputs[0]);
Browser1.Navigate(websites[1]);
}
if (Browser1.Url.ToString().Contains(websites[1]))
{
while (Browser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
Browser1.Document.GetElementById("mainsearchtext").SetAttribute("value", inputs[1]);
Browser1.Navigate(websites[2]);
}
if (Browser1.Url.ToString().Contains(websites[2]))
{
Browser1.Document.GetElementById("search-input").SetAttribute("value", inputs[2]);
}
SCOND WAY;
int n;
private void Browser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
n++;
if (n == 1)
{
Browser1.Document.GetElementById("email").SetAttribute("value", inputs[0]);
Browser1.Navigate(websites[1]);
}
if (n == 2)
{
Browser1.Document.GetElementById("mainsearchtext").SetAttribute("value", inputs[1]);
Browser1.Navigate(websites[2]);
}
if (n == 3)
{
Browser1.Document.GetElementById("search-input").SetAttribute("value", inputs[2]);
}
In second way problem is that n sometimes can be differently than expected.
I have problem with load second and third website. I also try on some another ways but don't work. So my goal is to open the pages one after the other and do some tasks on every page. If you have some another way, I would be grateful.
Perhaps try something like this:
int current = 0;
string[] websites = { "www.facebook.com", "www.bug.hr", "www.htmlgoodies.com" };
string[] elements = { "email", "mainsearchtext", "search-input" };
string[] inputs = { "first", "second", "third" };
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate(websites[current]);
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
timer1.Interval = 250;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
timer1.Stop();
webBrowser1.Document.GetElementById(elements[current]).SetAttribute("value", inputs[current]);
if (++current < websites.Length)
{
webBrowser1.Navigate(websites[current]);
}
}
}

Getting my calculator to take a new number after the equal button is pressed

So I have been at this for a while now and still cannot get my calculator to do one final thing.
I got it thanks!
After I push the equal button or Tan, Sin, Cos or Mod buttons I want my calculator to take a new number. Basically as if nothing was in the textbox even though the answer is still there. Currently, all the numbers stay and the new number is added to the end. I do not want this to happen.
After the calculation, if I push a number button I want it to clear the screen and add the new number fresh. Below is my code that I have so far.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Double FirstNumber;
string mathOperator = "";
private void AddButton_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
mathOperator = "+";
DisplayTextBox.Text = "";
DisplayTextBox.Focus();
}
private void EqualButton_Click(object sender, EventArgs e)
{
Double SecondNumber;
SecondNumber = Convert.ToDouble(DisplayTextBox.Text);
switch (mathOperator)
{
case "+":
DisplayTextBox.Text = (FirstNumber + SecondNumber).ToString();
break;
case "-":
DisplayTextBox.Text = (FirstNumber - SecondNumber).ToString();
break;
case "*":
DisplayTextBox.Text = (FirstNumber * SecondNumber).ToString();
break;
case "/":
DisplayTextBox.Text = (FirstNumber / SecondNumber).ToString();
break;
default:
break;
}
}
private void button12_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
FirstNumber *= -1;
DisplayTextBox.Text = FirstNumber.ToString();
}
private void ButtonMinus_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
mathOperator = "-";
DisplayTextBox.Text = "";
DisplayTextBox.Focus();
}
private void ButtonMultiply_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
mathOperator = "*";
DisplayTextBox.Text = "";
DisplayTextBox.Focus();
}
private void ButtonDivide_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
mathOperator = "/";
DisplayTextBox.Text = "";
DisplayTextBox.Focus();
}
private void ButtonMod_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
DisplayTextBox.Text = Math.Tan(FirstNumber).ToString();
}
private void Button1_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "1";
}
private void Button2_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "2";
}
private void Button3_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "3";
}
private void Button4_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "4";
}
private void Button5_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "5";
}
private void Button6_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "6";
}
private void Button7_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "7";
}
private void Button8_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "8";
}
private void Button9_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "9";
}
private void ButtonClear_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = "";
mathOperator = "";
}
private void ButtonOff_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void ButtonTan_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
DisplayTextBox.Text = Math.Tan(FirstNumber).ToString();
}
private void ButtonSin_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
DisplayTextBox.Text = Math.Sin(FirstNumber).ToString();
}
private void ButtonCos_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
DisplayTextBox.Text = Math.Cos(FirstNumber).ToString();
}
private void Button0_Click(object sender, EventArgs e)
{
if (DisplayTextBox.Text.Length >= 1)
{
DisplayTextBox.Text = DisplayTextBox.Text + "0";
}
else
{
return;
}
}
private void DecimalButton_Click(object sender, EventArgs e)
{
if (DisplayTextBox.Text.Contains("."))
{
return;
}
else
{
DisplayTextBox.Text = DisplayTextBox.Text + ".";
}
}
}
Add a Boolean variable to your class that represents a flag of whether or not an operation has just completed or not, like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Double FirstNumber;
string mathOperator = "";
bool operationJustCompleted = false;
Initially, the value will be false, because nothing has happened when the calculator is first created.
Now, at the end of the equal button event handler, set the flag to true, like this:
private void EqualButton_Click(object sender, EventArgs e)
{
// Logic for calculation
operationJustCompleted = true;
}
Finally, in the event handlers for the number buttons, check to see if the operationJustCompleted flag is true, if so then clear the text and reset the operation just completed flag back to false; like this:
private void Button1_Click(object sender, EventArgs e)
{
if(operationJustCompleted)
{
DisplayTextBox.Text = String.Empty;
operationJustCompleted = false;
}
DisplayTextBox.Text = DisplayTextBox.Text + "1";
}
Add a state variable to your class. When true, and a number is selected, clear the display and set it false before writing the number.
When "=" is clicked, set it true.
Based on a brief review, seems like you need to introduce a variable that will keep track of the calculator’s state, and then when “equal” button is pressed, set the state to calculated value. Then, in the numeric buttons (0-9) you need to check the state variable and either append to or replace the display text.
Create this global variable...
private bool equationComplete = false;
Add this to the end of the Equals button...
equationComplete = true;
Add this to the beginning of each number button click...
if (equationComplete) DisplayTextBox.Text = "";
Add this to the end of each number button click event handler...
equationComplete = false;
Just like David Arno says, something like this:
private void EqualButton_Click(object sender, EventArgs e)
{
ClearDisplayBeforeNextTextEntry = true;
}
private void Button1_Click(object sender, EventArgs e)
{
// New code
ClearText();
// Old code
DisplayTextBox.Text = DisplayTextBox.Text + "1";
}
// Same for all other number buttons as above
private void ClearText()
{
if (ClearDisplayBeforeNextTextEntry)
{
DisplayTextBox.Text = "";
ClearDisplayBeforeNextTextEntry = false;
}
}

Panel not displaying when it should be

So in my very small program I am generating a random percentage and based off that percentage it should display one of two panels. However, it is only ever displaying one.
Here is my code:
Random random = new Random();
private void button1_Click(object sender, EventArgs e)
{
bool button1Clicked = true;
if (button1Clicked == true) { ITIpanel.Visible = true; }
}
private void ITIpanel_Paint(object sender, PaintEventArgs e)
{
ITItimer.Enabled = true;
}
private void ITItimer_Tick(object sender, EventArgs e)
{
double rand = random.NextDouble();
if (rand <= .50) { bluestimPanel.Visible = true; }
if (rand >= .50) { redstimPanel.Visible = true; }
ITItimer.Enabled = false;
}
private void bluestimPanel_Paint(object sender, PaintEventArgs e)
{
Trialtimer.Enabled = true;
}
private void redstimPanel_Paint(object sender, PaintEventArgs e)
{
Trialtimer.Enabled = true;
}
private void Trialtimer_Tick(object sender, EventArgs e)
{
bluestimPanel.Visible = false;
redstimPanel.Visible = false;
Trialtimer.Enabled = false;
ITIpanel.Visible = true;
}
I think what is happening here is that in the TrialTimer_Tick method setting ITIPanel.Visible to true is not causing ITIPanel to repaint and hence ITITimer never restarts.
You can put a breakpoint in the ITITimer_Click method and see if it is ever invoked again after the first invocation.

Categories

Resources