Unwanted Char Appears - c#

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;

Related

How can I find the last character of a textbox text?

I am a beginner in C#. I am making a web calculator like Microsoft Desktop calculator with the help of asp.net. But I'm stuck at one place. My code for Plus, minus, multiply or div is like:
protected void btnPlus_Click(object sender, EventArgs e)
{
if (txtBox1.Text.EndsWith("+"))
{
txtBox1.Text = txtBox1.Text;
}
else
{
txtBox1.Text = txtBox1.Text + "+";
ViewState["Operation"] = "+";
}
}
But I want to check this condition for all operations like minus, multiply and divide. I don't want Plus, Minus, Multiply or Div signs appear in the textbox.
You can store all your operators in a string constant and check if the last character is contained in that string:
private const string OPERATORS = "+-/*";
protected void btnPlus_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtBox1.Text) || // check if string is empty
OPERATORS.Contains(txtBox1.Text.Last())) // or if last character is a operator
{
txtBox1.Text = txtBox1.Text;
}
else
{
txtBox1.Text = txtBox1.Text + "+";
ViewState["Operation"] = "+";
}
}
You can do something like the following:
Extract last character
Based on the character assign operator to the view state
If it is any operator then remove them from the textbox
Finally do the operation
if (txtBox1.Text != "")
{
char last_char = txtBox1.Text[txtBox1.Text.Length - 1];
switch (last_char)
{
case '+':
ViewState["Operation"] = "+";
txtBox1.Text.Remove(txtBox1.Text.Length - 1);
break;
case '-':
ViewState["Operation"] = "-";
txtBox1.Text.Remove(txtBox1.Text.Length - 1);
break;
// do the same for all operators
default:
break;
}
}

Just need some help regarding a calculator C#

I am making a calculator to gain some experience with C#, atm i have one textbox ontop of one another, the lower one is called calculation; i want this one to show the sum being calculated. The text box on top is called result and i obviously want that to display the result; the result box works fine. I want the lower text box ( called calculation ) to display the + symbol which it wont let me do and at the moment i am only able to show the digits. I assume this is a data type problem. Any help/advice? thank you! (I'm sorting this out before moving onto the other symbols and eventually putting it into a switch case :) )
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double num1 = 0;
double num2 = 0;
private void Clearbtn_Click(object sender, EventArgs e)
{
Calculation.Clear();
Result.Clear();
}
private void Numericclick(object sender, EventArgs e)
{
Button button = (Button)sender;
Calculation.Text = Calculation.Text + button.Text;
}
private void Plusbtn_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(Calculation.Text);
Result.Show();
}
private void Equalsbtn_Click(object sender, EventArgs e)
{
num2 = num1 + double.Parse(Calculation.Text);
Result.Text = num2.ToString();
num1 = 0;
}
}
}
If you use the (+) operator with strings it concatenates them together.
This line Calculation.Text = Calculation.Text + button.Text;
In C# 6 will be this:
Calculation.Text = $"{Calculation.Text} + {button.Text}";
Lower than C# 6:
Calculation.Text = string.Format("{0} + {1}", Calculation.Text, button.Text);
String Concatenation Documentation: HERE
Example of difference between the operand + and as a string "+":
//+ operand concats string
var text = "abc";
var text2 = "def";
var result = text + text2;
//result -> "abcdef"
var result2 = text + "+" + text2;
//result -> "abc+def"

convert string to double not working?

I'd like to convert a string to a double. I know, it has been asked before, but let me finish it! :)
So I read the string in from a USB port (Arduino experiment), and I'd like to add that value to a list of doubles. The values are coming in continuously.
The problem is, when I try to convert the string to double it gives an error message that says: "The format of the incoming character chain is wrong" or something like this. I get this error message with both the parse and convert command.
What should I do?
Here's the part of the code that supposed to do the job:
namespace voltmeres{
public partial class Form1 : Form
{
List<double> lista = new List<double>();
int i;
double f;
string POT;
public Form1()
{
InitializeComponent();
serialPort1.PortName = "COM5";
serialPort1.BaudRate = 9600;
lista.Capacity = 100;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
POT =serialPort1.ReadExisting();
textBox1.Text = POT.ToString();
}
f = Convert.ToDouble(textBox1.Text);
lista.Add(f);
i++;
if (i == lista.Capacity)
{
lista.Capacity=lista.Capacity + 100;
}
}
From the comments, it looks like it's a number formatting issue. Try the following:
f = Convert.ToDouble(textBox1.Text, new System.Globalization.CultureInfo("en-US"));
Try this
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
POT = serialPort1.ReadExisting();
textBox1.Text = POT.ToString();
}
if (! double.TryParse(textBox1.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out f)) return;
f = Convert.ToDouble(textBox1.Text);
lista.Add(f);
i++;
if (i == lista.Capacity)
{
lista.Capacity = lista.Capacity + 100;
}
}
You should use double.TryParse instead. It will parse if it is a double, else it will not throw an exception.
if(double.TryParse(textBox1.Text,outf))
{
lista.Add(f);
i++;
if (i == lista.Capacity)
{
lista.Capacity=lista.Capacity + 100;
}
}
If the above answers don't work, try 'String.valueOf(your double);' This should do the trick if your double is correct.
Another suggestion : depending on the double you have, for instance if it is a really long double, you may want to format the value before or after the conversion to take only a few digits.

How do I stop a single button from hiding my textbox during a specific event?

I have two questions:
1) Is this the correct way to make my default value = 0 for variables, then pass a value given by the user into that variable?
protected void btnCheck_Click(object sender, EventArgs e)
{
lblYesNo.Text = "";
//default int values are set to 0
int remainder = 0;
int guess = 0;
remainder = int.Parse(txtRemainder.Text);
guess = int.Parse(txtAnswer.Text);
answer = (int)Session["answer"];
if (guess == answer)
{
lblYesNo.Text = lblYesNo.Text + "Correct!";
}
else
{
lblYesNo.Text = lblYesNo.Text + "Try Again..";
}
}//END Check Answer
2) how can I stop the Check_Click(submit button) from hiding the txtRemainder(textbox)? The reason it 'auto-hides' now is because I set the default value to 'txtRemainder.Visible = false;' in the Page_Load, which will make it hide unless the math problem is division. When I click on the btnDiv_Click(divide button) it resets it to 'txtRemainder.Visible = true;', because this provides a division question to be solved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class BasicMath : System.Web.UI.Page
{
int number1;
int number2;
int answer;
protected void Page_Load(object sender, EventArgs e)
{
txtRemainder.Visible = false;
}
protected void GetRandom()
{
Random rand = new Random();
number1 = rand.Next(0, 10);
number2 = rand.Next(0, 10);
txtAnswer.Text = "";
txtRemainder.Text = "";
lblYesNo.Text = "";
}//END Get Random Number
protected void btnAdd_Click(object sender, EventArgs e)
{
GetRandom();
lblEquation.Text = number1.ToString() + " + " + number2.ToString();
answer = number1 + number2;
Session["answer"] = answer;
}//END Addition Button
protected void btnSub_Click(object sender, EventArgs e)
{
GetRandom();
if (number2 > number1)
{
answer = number2 - number1;
lblEquation.Text = number2.ToString() + " - " + number1.ToString();
}
else
{
answer = number1 - number2;
lblEquation.Text = number1.ToString() + " - " + number2.ToString();
}
Session["answer"] = answer;
}//END Subtraction Button
protected void btnMult_Click(object sender, EventArgs e)
{
GetRandom();
lblEquation.Text = number1.ToString() + " x " + number2.ToString();
answer = number1 * number2;
Session["answer"] = answer;
}//END Multiplication Button
protected void btnDiv_Click(object sender, EventArgs e)
{
Random rand = new Random();
number1 = rand.Next(1, 10);
number2 = rand.Next(1, 10);
/*will only display the txtRemainder(textbox) while using the Divide button,
txtRemainder will auto-hide when using another button because
it's default setting of '.Visible = false' is placed in the Page_Load*/
txtRemainder.Visible = true;
lblEquation.Text = number1.ToString() + " / " + number2.ToString();
answer = number1 / number2;
Session["answer"] = answer;
}//END Division Button
protected void btnCheck_Click(object sender, EventArgs e)
{
lblYesNo.Text = "";
//default int values are set to 0
int remainder = 0;
int guess = 0;
remainder = int.Parse(txtRemainder.Text);
guess = int.Parse(txtAnswer.Text);
answer = (int)Session["answer"];
if (guess == answer)
{
lblYesNo.Text = lblYesNo.Text + "Correct!";
}
else
{
lblYesNo.Text = lblYesNo.Text + "Try Again..";
}
}//END Check Answer
}
If this question doesn't make sense please ask for clarification.
Question 1:
Yes, that is the correct way to initialize your variables to default values of zero, although int variables are initialized to zero by default, so even if you omitted the assignment, they would still default to zero.
The method you're using to accept the user input is correct, but could throw an exception if the values entered by the user are not Int32 values (think 3.2). As it stands, you have no try..catch blocks to deal with these exceptions. You could either add these try..catch blocks, or you could use the TryParse() method to check that the values are valid. For example:
protected void btnCheck_Click(object sender, EventArgs e)
{
lblYesNo.Text = "";
//default int values are set to 0
int remainder = 0;
int guess = 0;
if (!Int32.TryParse(txtRemainder.Text, out remainder))
{
// do something here to inform the user that remainder is invalid
return;
}
if (!Int32.TryParse(txtAnswer.Text, out remainder))
{
// do something here to inform the user that answer is invalid
return;
}
answer = (int)Session["answer"];
if (guess > answer)
{
lblYesNo.Text = lblYesNo.Text + "Try Again..";
}
else if (guess < answer)
{
lblYesNo.Text = lblYesNo.Text + "Try Again..";
}
else
{
lblYesNo.Text = lblYesNo.Text + "Correct!";
}
}//END Check Answer
TryParse() will convert the value into the output variable if it's a valid value & return true to indicate success, otherwise it will return false if it was not able to perform the conversion.
Question 2:
In order to hide txtRemainder when the page first loads & then to keep it hidden if any button was clicked other than btnDiv, here is a proposed solution. First, the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
lblTest.Visible = false;
} else {
foreach (string ctrl in Request.Form) {
Control c = FindControl(ctrl);
if (c is Button) {
txtRemainder.Visible = c.ID == "btnDiv";
return;
}
}
}
}
Now for some explaining. When the page initially loads, the label is hidden (by the !IsPostBack check). If the request is indeed a postback, we go through the collection of returned form controls (contained in the Request.Form collection) & check to see if a button is present that could have caused the postback. Buttons are rendered in the HTML as <input type="submit" .. /> elements, and upon postback, only the button that was clicked is sent back in the Form collection, even if there are multiple submits on the page. A more detailed explanation can be found here
Now, if a button did indeed cause the postback, then we check to see if this button was btnDiv. If it was, the comparison returns true & txtRemainder is displayed. If not, it is hidden.
This way, there is no need to show or hide txtRemainder in each event handlers. You wouldn't even need to set it to visible in the event handler for btnDiv.
EDIT
Based on the requirement listed in the comments, I've altered my answer to question 2 so as to provide an alternative method to having to show or hide the label in each button event.
Question1:
If you are using .Net 4.0 and up, consider using the TryParse method, and check the result for success, this way you have better control over parsing values and trapping exceptions
e.g.
int number = 0;
bool result = false;
result = int.TryParse("123", out number);
if (!result)
{
throw new InvalidCastException("Error converting number");
}
Question2:
It looks like you're using Asp.Net, so try testing for Page.IsPostBack in your Page_Load event, this way you can determine whether the page loads because of an initial load, or because you sent data to the server i.e. clicked a button.
Hope this helps!

Why my form is getting closed when i move the Tab to and fro from the textbox

I have the following code in my TextBox leave event:
private void txtAmount_Leave(object sender, EventArgs e)
{
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
But if move back to the previous control by hitting Shift+Tab and again moving back to the same textbox and then trying to move to other the form is getting closed automatically. Why does this happen?
The call to Convert.ToInt32() is probably throwing an exception, likely due to being unable to convert the string in your TextBox to an integer. Convert.ToInt32() can throw the following exceptions (descriptions from MSDN):
FormatException - value does not consist of an optional sign followed by a sequence of digits (0 through 9).
OverflowException - value represents a number that is less than Int32.MinValue or greater than Int32.MaxValue.
It's likely a FormatException, thrown when you leave the TextBox after the $ is prepended to your string, or after you enter any non-numeric characters (letters, etc). To fix this, you have a couple of options:
Add a try / catch block around your code to handle any exceptions.
Use Int32.TryParse() instead of Convert.ToInt32().
Add some code that will prevent non-numeric characters from being entered in your TextBox
Here's an improved version of your event handler:
private void txtAmount_Leave(object sender, EventArgs e)
{
string toParse = txtAmount.Text.TrimStart('$');
int parsed;
if (Int32.TryParse(toParse, out parsed))
{
double res = (double)parsed / 100;
txtAmount.Text = "$" + res.ToString();
}
}
The first time you leave this textbox, its contents will be changed to "$123" (for example). The second time you leave, trying to convert that to int will throw an exception.
You could use the overload of TryParse that takes a NumberStyle, something like this, assuming your goal is to just show a currency value with no decimal places.
double number;
if (double.TryParse(txtAmount.Text, NumberStyles.Currency, CultureInfo.CurrentUICulture, out number))
{
txtAmount.Text = number.ToString("C0");
}
else
{
MessageBox.Show("Could not convert.");
}
After reading #Donut's comment on his answer, I am not sure what your goal is. If you'd like to truncate the cents off but still show the ".00", you can do this:
txtAmount.Text = ((int)number).ToString("C");
Or do this, which will round:
txtAmount.Text = (Convert.ToInt32(number)).ToString("C");
If this does not help, please clarify and let us know what you are trying to accomplish.
Try this:
private void txtAmount_Leave(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtAmount.Text) && txtAmount.Text.StartsWith("$"))
txtAmount.Text = txtAmount.Text.Substring(1);
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
Check the txtAmount.Text for the $ sign, before trying to convert it to an int. If the $ sign is present, strip it out, and convert the rest of the input to an int.
Also, you might want to use the Int32.TryParse method, as that will help you figuring out whether the entered text can be converted into an int or not.
You may want to change your code to remove the $ before working with the number:
private void txtAmount_Leave(object sender, EventArgs e)
{
int x = 0;
int.TryParse(txtAmount.Text.Replace("$", string.Empty), out x);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
I got the solution
private void txtAmount_Leave(object sender, EventArgs e)
{
string strAmnt = string.Empty;
strAmnt = txtAmount.Text;
if (strAmnt.Contains(".") && !strAmnt.Contains("$"))
{
txtAmount.Text = "$" + strAmnt;
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}
else
if (strAmnt.Contains("$") && !strAmnt.Contains("."))
{
Int64 amnt = 0;
strAmnt = strAmnt.Replace("$", "");
try
{
amnt = Convert.ToInt64(strAmnt);
double amt = (double)amnt / 100;
txtAmount.Text = "$" + amt.ToString();
}
catch (FormatException ie)
{
MessageBox.Show("Invalid Format");
}
}
else
if (!strAmnt.Contains(".") && !strAmnt.Contains("$"))
{
try
{
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}
catch (FormatException ie)
{
MessageBox.Show("InvalidFormat");
}
}
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}

Categories