I would like to see label6 display the number of correct times the user chooses the number. And label7 display the number of times the user choose incorrectly. Its not incrementing by one.
Error 1 Operator '++' cannot be applied to operand of type 'string'
Error 2 Operator '++' cannot be applied to operand of type 'string'
private void button1_Click(object sender, EventArgs e)
{
string correct="0";
string incorrect="0";
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
label3.Text=("Winner");
label6.Text = correct +1;
if (textBox1.Text != label1.Text)
label7.Text = incorrect= +1;
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
Edit (From OP's answer to his own question):
I have tried the ways your suggesting but the number doesnt increase by one everytime I guess wrong.
private void button1_Click(object sender, EventArgs e)
{
int correct=0;
int incorrect=0;
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text = ("Winner");
label6.Text = (++correct).ToString();
}
else if (textBox1.Text != label1.Text)
{
label7.Text = (incorrect+1).ToString();
label3.Text = (string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
}
It doesn't look like you're persisting the correct and incorrect
Create Properties:
public int Correct { get; set; }
public int Incorrect { get; set;}
Then:
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++this.Correct).ToString();
}
else
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++this.Incorrect).ToString();
}
}
You are storing your correct and incorrect variables as string.
Use int instead like this:
int correct = 0;
int incorrect = 0;
and change your code to:
correct++;
label6.Text = correct.ToString();
and:
incorrect++;
label7.Text = incorrect.ToString();
Adding to strings, correct and incorrect will just append the string representation of what's added. You have to convert it to an integer type, then increment, then convert back to string. However it would be easier to just keep these variables as integer instance variables. That way incrementing is trivial and you are actually keeping the correct count and not resetting every time the button gets clicked. (There are actually a number of problems with the code)
// instance variables
private int correct = 0;
private int incorrect = 0;
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++correct).ToString(); // convert int to string
}
// indentation does not indicate the block
else //if (textBox1.Text != label1.Text)
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++incorrect).ToString();
}
}
Or you can use:
correct = correct + 1; ( I think this is what you were trying to achieve)
incorrect = incorrect + 1;
OR
correct += 1;
incorect += 1;
label6.Text = correct +1;
only sets label6's value to correct + 1; it does not change the value of correct. If you use:
int correct;
label6.Text = (++correct).ToString();
you should see what you want.
Related
I am beginner , am trying to create a calculator. the way of the code working is there is a method for summing and one for subtraction ETC.
when i call the subtraction method unwanted minus appears before the answer in the textbox ( i know my code could be using harder way to do the same purpose but i am just beginner trying to do some code )
double rat;
byte operations;
public void TheEqualMinus(double earlier) //Substraction Operation Method
{
double _minus;
_minus = Convert.ToDouble(result.Text);
double last = _minus - earlier;
result.Text = last.ToString();
}
private void button15_Click(object sender, EventArgs e)
{
//The Subtract Button
operations = 2;
rat = Convert.ToDouble(result.Text);
label1.Text = rat + " -";
result.Text = "";
}
private void button4_Click(object sender, EventArgs e)
{
// equal button
NewText = true; //boolean to newtext
switch (operations)
{
case (1): //addition
TheEqualSum(rat);
label1.Text = "";
break;
case (2): //substraction
TheEqualMinus(rat);
label1.Text = "";
break;
}
}
and the answer output becomes " - The Correct Answer i want "
ex. 9-6 = -3
so any ideas how to remove this minus ?
As per the comments above, this was fixed by simply changing this:
double last = _minus - earlier;
to this:
double last = earlier - _minus;
I'm creating a calculator and I want to add validation code in it, so that if anything besides numbers is entered, an error message appears.
private void button4_Click(object sender, EventArgs e)
{
int R = Convert.ToInt32(textBox1.Text);
int I = Convert.ToInt32(textBox2.Text);
int number2;
if (int.TryParse(textBox1.Text, out number2))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
textBox2.Text = ("value entered is not whole number");
}
}
This is the code I am trying to use but it comes up with an error message when I enter a non-numeric value.
You are calling Convert.ToInt32 method before TryParse and that causes the exception. Don't do that, do the validation with TryParse.
private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R) &&
int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
MessageBox.Show("You have entered an invalid value!");
}
}
Also you might consider using more descriptive variable names instead of E, R, I...
private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R)
&& int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else { textBox3.Text = ("value entered is not whole number"); }
}
Make sure you try to parse the strings into ints with TryParse always, rather than just converting immediately... if there are letters, the conversion fails.
private void button4_Click(object sender, EventArgs e)
{
int number1;
int number2;
if (int.TryParse(textBox1.Text, out number1) && int.TryParse(textBox2.Text, out number2))
{
//do your thang (subtraction, assigning the result to TextBox3)
//return
}
else
{
MessageBox.Show("Oh no you entered something that's not an int!");
}
}
I might also add that making the value of one of your input text boxes "Value entered is not a whole number" is kind of a weird UI experience. I'd mark the textbox in red or pop up a message box or something instead, leaving the entered value in the box, in case it was some really long number like 879320!78 where they accidentally entered a weird symbol or something.
private void button1_Click(object sender, EventArgs e)
{
double temp = double.Parse(textBox1.Text);
if (temp < 0)
{
label2.Text = "Freezing.";
}
if (temp > 40)
{
label2.Text = "Hot.";
}
else
{
label2.Text = "Moderate.";
}
}
Whenever converting user input, or any form of type String in to an object, I always like to use TryParse(...) as it provides you with better control if something isn't right.
double temp = 0.0d;
var converted = double.TryParse(textBox1.Text, out temp);
if (!converted) throw new Exception("Please enter a positive or negative temperature.");
if (temp < 0.0d)
{
// Freezing
}
else if (temp >= 0.0d && temp < 40.0d)
{
// Moderate
}
else if (temp >= 40.0d)
{
// Hot
}
The key is finding out what the value is being read in to temp. If its bringing in a negative number then I would recommend the code change below. What its really doing is if the 1st isnt true, then it checks the second, and finally it uses the third if neither are true.
private void button1_Click(object sender, EventArgs e)
{
double temp = double.Parse(textBox1.Text);
if (temp < 0)
{
label2.Text = "Freezing.";
}
else if (temp > 40)
{
label2.Text = "Hot.";
}
else
{
label2.Text = "Moderate.";
}
}
I am new to C#. I'm trying to make a calculator, but the following error occurred:
Input string was not in a correct format.
This is the summary of the code:
double num1, num2, result;
private void button14_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(textBox1.Text);
textBox1.Text = String.Empty;
num2 = double.Parse(textBox1.Text); **//ERROR OCCURED HERE**
result = num1 - num2;
}
private void button13_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(textBox1.Text);
textBox1.Text = String.Empty;
num2 = System.Double.Parse(textBox1.Text); **//ERROR OCCURED HERE**
result = num1 + num2;
}
How to convert string to a double type?
Also remember that the Parse method is relying on the culture of your operating system to perform the conversion, so try to change your code to
num2 = double.Parse(textBox1.Text, CultureInfo.InvariantCulture);
You might also consider to use the
double.TryParse
method for better exception handling.
What are you trying to achieve with this code? It seems that your algorythm is wrong.
Like others said, this code
textBox1.Text = String.Empty;
num2 = double.Parse(textBox1.Text);
will throw an Exception because an empty string cannot be converted to Double!
So, I'm wondering why did you reset your field. I thought about it for a while, and maybe I got what are you trying to do. Let's say you type a number in TextBox1. Then you press the "-" button to subtract and then you want to enter the second number to view the result. Is this the case? If it is, the code you wrote is not going to wait for your next input!
In fact, when you click the button, it just executes all the lines you wrote. I'd write something like this instead.
double num1, num2, result;
string operation;
private void button14_Click(object sender, EventArgs e) //Minus Button
{
if (textBox1.Text != String.Empty) //Added if statement to see if the textBox is empty
num1 = Convert.ToDouble(textBox1.Text);
else
num1 = 0; //If textBox is empty, set num1 to 0
textBox1.Text = String.Empty;
operation = "-";
}
private void button13_Click(object sender, EventArgs e) //Equals Button
{
if (textBox1.Text != String.Empty)
num2 = Convert.ToDouble(textBox1.Text);
else
num2 = 0;
if (operation == "-")
{
result = num1 - num2;
textBox1.Text = Convert.ToString(result);
}
if (operation == "+")
{
//You got it
}
//And so on...
}
EDIT: If the string is empty, this is going to always throw Exceptions, so I added a control. If the string is empty, value becomes zero.
Since you have cleared the textbox on the previous line, the Parse conversion fails.
textBox1.Text = String.Empty;
num2 = double.Parse(textBox1.Text);
How will it convert String.Empty to Double?
The way of doing it is not right.
For example, if the "+" button is clicked, you have to check whether there was already a number. If so,, add the numbers and display the result:
Double num;
private void Add_Click(object sender, EventArgs e)
{
If (num != null)
{
num == num + Convert.ToDouble(textBox1.Text);
}
else
{
num1 == Convert.ToDouble(textBox1.Text);
}
textBox1.Text = num;
}
Seems like num2 value should be fetched from textbox2 not textbox1(You are setting textbox1.text to empty and trying to parse it to double again)
//You are setting textbox1 to empty
textBox1.Text = String.Empty;
//here trying to parse it to double
num2 = double.Parse(textBox1.Text);
Also don't use Convert.ToDouble(textBox1.Text) directly. if users type non numeric values your code will crash. first check if its a valid number, always use doube.TryPrase()
double num1;
double.TryParse(textBox1.Text, out num1);
Your code seems hard to understand whats the use of button_13 and button_14;
I will assume your trying to do this:
bool ifNew = true;
double num1 ,num2,result;
private void Add_Click(object sender, EventArgs e))
{
if(ifNew)
{
num1 = Convert.ToDouble(textBox1.Text);
textbox1.Clear();
ifNew = false;
result += num1;
}
else
{
num2 = Convert.ToDouble(textBox1.Text);
textbox1.Clear();
result += num2;
num1 = 0D;
num2 = 0D;
ifNew = true;
}
}
private void Equals_Click(object sender, EventArgs e)
{
textboxl.Text = string.Format("{0:N}",result);
}
Or you could use Double.Parse in my Convert.ToDouble
It depends on your operation but I am visualizing
how to do add operation you can change and edit this
depends on your operation
I want to write the event handler method button1_Click to calculate whether student’s Grade is “PASS” or “FAIL”. The student passes the course if the total score is greater than or equal to 50. The total score is Midterm(textbox1) + Final(textbox2) scores. However, teacher can give student Extra Credit(checkbox1) which is worth 10 points. The result will present in the textBox3
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
int midtermInt = int.Parse(textBox1.Text);
int finalInt = int.Parse(textBox2.Text);
if (checkBox1.Checked)
{
if ((midtermInt + finalInt) + 10 >= 50)
{
grade.Text = "PASS";
}
else if ((midtermInt + finalInt) + 10 < 50)
{
grade.Text = "FAIL";
}
}
else if (!checkBox1.Checked)
{
if ((midtermInt + finalInt) >= 50)
{
grade.Text = "PASS";
}
else if ((midtermInt + finalInt) < 50)
{
grade.Text = "FAIL";
}
}
When I run it, it says "Inut string was not in a correct format.. :(
I'm very new to C# please advise me if my code is wrong anywhere
The input will only be integers never texts..
You should use int.TryParse insted int.Parse, it's check is specified string is in correct format.
You code may looks like this:
int midtermInt;
if (!int.TryParse(textBox1.Text, out midtermInt))
{
labelError.Text = "Icorrect value in field 'textBox1'".
return;
}
If you type non-numeric characters in your textbox and try to parse the text, it will throw you this exception. Try trimming the input and definitely consider adding UI validation to your forms.
You can add checking, if text in text box is in correct format in TextChanged event:
private void textBox_TextChanged(object sender, EventArgs e)
{
int val;
if (textBox.Text.Length == 0 || !int.TryParse(textBox.Text, out val))
tsPassingScore.Text = "0";
}
And in your click you can check if there is number in textBox again with int.TryParse
Also you can improve your code:
If final summ is not bigger then 50 - it is automatically smaller! And it would be more readable, if you introduce extra variable - for teachers extra credit:
int extraCredit = checkBox1.Checked ? 10 : 0;
int finalScore = midtermInt + finalInt + extraCredit;
if (finalScore >= 50)
grade.Text = "PASS";
else
grade.Text = "FAIL";