I'm working with Microsoft Visual C# 2010 Express. I am currently trying to get my calculator to do addition and subtraction but I keep getting this error? I am using switch statements throughout the calculator.
private void Add_Click(object sender, EventArgs e)
{
//Storing the number on display in variables total1 for further use
//Making addition happen before = is clicked
total1 = total1 + double.Parse(textDisplay.Text);
textDisplay.Text = textDisplay.Text + Add.Text;
theOperator = "+";
}
private void Subtract_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(textDisplay.Text);
textDisplay.Clear();
theOperator = "-";
}
private void Equals_Click(object sender, EventArgs e)
{
switch(theOperator)
{
case "+": //Addition
total1 = total1 + double.Parse(textDisplay.Text);---> error in this line
textDisplay.Text = result.ToString();
total1 = 0;
break;
case "-": //Subtraction
result = total1 - double.Parse(textDisplay.Text);--->error in this line
textDisplay.Text = result.ToString();
total1 = 0;
break;
On your problem lines, you have:
double.Parse(textDisplay.Text)
But in your Add_Click method you have this:
textDisplay.Text = textDisplay.Text + Add.Text;
I am hypothesizing that that your Add button label is not a number (likely it is either Add or +). So when you run the line above, you would get something like either:
1234Add
1234+
This will cause an exception in when you pass it to double.Parse because this function does not accept bad input (so unless textDisplay.Text is a number, it will give an error). You would want to use double.TryParse instead if you want to test for bad input.
Here is an example on how to test for bad input:
private void Equals_Click(object sender, EventArgs e)
{
// Remove the operator from the value we want to process.
// It is expected this will be at the end.
var userValue = textDisplay.Text;
if (userValue.EndsWith(theOperator))
{
userValue = userValue.Substring(0, userValue.Length - theOperator.Length).Trim();
}
// Test for valid input.
// Test our "userValue" variable which has the pending operator removed.
double value;
if (!double.TryParse(userValue, out value))
{
// Invalid input.
// Alert the user and then exit this method.
MessageBox.Show("A number was not entered.");
return;
}
// If we get here, the "value" variable is a valid number.
// Use it for calculations.
...
Edit
As a side note, you do have some logic issues with respect to how you are using and resetting result and total1 in your OP. I'm not going to do your homework for you, but it would be a good idea to review your usages of these variables.
Related
Amateur here making a C# calculator in visual studio and want to save inputs as 'operand1' and 'operand2' such that I can display the history of inputs/calculations. Example of my first thought:
private void twoBtn_Click(object sender, EventArgs e)
{
if (txtBox.Text == "0")
{
txtBox.Text = "2";
}
else
{
txtBox.Text += "2";
}
}
The issue is that it simply adds that to the text box, which is fine for calculations, but I have no way of retrieving that input data after it's cleared.
I've tried setting it up like this:
private void oneBtn_Click(object sender, EventArgs e)
{
if (operand1 == null)
{
operand1 = 1;
txtBox.Text = operand1.ToString();
return;
}
if (operand2 != null) return;
operand2 = 1;
txtBox.Text = operand2.ToString();
}
However, the issue here is that I cannot seem to input an operand which is more than 1 digit, making the only possible operands numbers 1-9. I understand I'm very new to the language and coding in general and would greatly appreciate anyone's insight as to what I'm missing!
I'm an absolute beginner when it comes to C#. Trying to learn via examples. So I've found myself a nice little calculator tutorial. Everything goes fine up to last moment, the code is working, but it doesn't take multi-digit input like 33. There's a bool statement there for turning arithmetic operations on/off and tutorial instructor figured, that we should put bool = false before the number input/button press (in button_Click).
His code looks like this:
public partial class MainWindow : Window
{
double value = 0;
string operation = "";
bool operation_pressed = false;
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
if ((tb.Text == "0") || (operation_pressed == true))
tb.Clear();
operation_pressed = false;
Button b = (Button)sender;
tb.Text += "\n" + b.Content.ToString();
}
private void operator_Click(object sender, RoutedEventArgs e)
{
Button b = (Button)sender;
operation = b.Content.ToString();
value = double.Parse(tb.Text);
operation_pressed = true;
equation.Content = value + " " + operation;
}
private void result_Click(object sender, RoutedEventArgs e)
{
equation.Content = "";
switch(operation)
{
case "+":
tb.Text = "\n" + (value + double.Parse(tb.Text)).ToString();
break;
case "-":
tb.Text = "\n" + (value - double.Parse(tb.Text)).ToString();
break;
case "*":
tb.Text = "\n" + (value * double.Parse(tb.Text)).ToString();
break;
case "/":
tb.Text = "\n" + (value / double.Parse(tb.Text)).ToString();
break;
default:
break;
}
}
private void CE_Click(object sender, RoutedEventArgs e)
{
tb.Text = "\n 0";
}
private void C_Click(object sender, RoutedEventArgs e)
{
tb.Clear();
equation.Content = "";
value = 0;
}
}
It compiles nicely. But when I try to input a multidigit number and follow it with a mathematical operator, it throws an exception for value = double.Parse(tb.Text); that states:
When converting string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
I'm so confused right now. There's no DateTime even involved! And I'm 100% positive, everything is like in the tutorial. What's going on? :/
Any help will be appreciated greatly!
EDIT
Screenshot of actual error:
First of all, you're interpreting the debugger incorrectly. This is not the error message:
When converting string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
Notice how it's listed as "Troubleshooting Tips". In the vast majority of cases, you can ignore it. The error message itself is in a language I don't know, so I can't speak to what it says. But a FormatException essentially means that you're trying to parse a value which can't be parsed.
Your screen shot cuts off some information, but what is the value of tb.Text? Is it one of those "+" strings? If so, then that's your problem.
"+" can't be parsed as a numeric value, because "+" isn't a number.
You can make your code a little more resistant to errors by using TryParse instead of Parse. Something like this:
double result;
if (!double.TryParse(tb.Text, out result))
{
// couldn't parse
}
If the if block isn't entered, then result will contain the successfully parsed value. If it is entered, then the value couldn't be parsed. How you handle that situation is up to you. An error message to the user, a default value instead of the parsed value, etc. That's application logic for you to define.
The point is, tb.Text contains a non-numeric value which you're trying to convert into a numeric value. Hence the error.
Try this code in operator_Click event
Button b = (Button)sender;
operation = b.Text;
value = Convert.ToDouble(tb.text)
double num1, num2, result;
String sign = "";
protected void add_Click(object sender, EventArgs e)
{
sign = "+";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
protected void equal_Click(object sender, EventArgs e)
{
try
{
num2 = double.Parse(Convert.ToString(tb1.Text));
if(sign.Equals("+")){
result = num1 + num2;
tb1.Text = Convert.ToString(result);
}
if(sign.Equals("-")){
result = num1 - num2;
tb1.Text = Convert.ToString(result);
}
if(sign.Equals("*")){
result = num1 * num2;
tb1.Text = Convert.ToString(result);
}
if(sign.Equals("/")){
result = num1 / num2;
tb1.Text = Convert.ToString(result);
}
}
catch (Exception ex)
{
tb1.Text = ex.Message;
}
}
protected void minus_Click(object sender, EventArgs e)
{
sign = "-";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
protected void divide_Click(object sender, EventArgs e)
{
sign = "/";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
protected void product_Click(object sender, EventArgs e)
{
sign = "*";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
this is my simple program which performs arithmetic operations, but when i click '=' button it does not gives me result instead it gives me the last number entered in the textfield..
anyone knows whats the problem with code?
Web applications are stateless, a new instance of your class is created for each request (GET or POST).
Therefore the fields in the class are reinitialized on every POST:
double num1, num2, result;
String sign = "";
You need to persist the values of these fields somewhere: ViewState would be one option.
A typical ViewState-backed property implementation would look something like:
public double Num1
{
get
{
o = ViewState["Num1"];
return (o == null) 0D : (double) o;
}
set
{
ViewState["Num1"] = value;
}
}
If you replace each of your fields num1, num2, result, sign with properties implemented like this (each with a unique name of course), and ViewState is enabled, then you should get the result you want.
The sign variable is being reset to an empty string on post back by this line:
String sign = "";
You need to store the value of sign in cache so that it survives between post backs.
I recommend Session to do that, like this:
protected void minus_Click(object sender, EventArgs e)
{
sign = "-";
// Store sign in Session
Session["theSign"] = sign;
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
Note: Do this same Session storing logic in the other event handlers for divide and product.
Now in Page_Load you need to check the Session for the sign value every time, like this:
protected void Page_Load(object sender, EventArgs e)
{
// Default sign value that may be changed by value in session cache
String sign = "";
// Is there a session value for theSign
if(Session["theSign"] != null)
{
// Yes, so set the sign variable value to use in click event handlers
sign = Session["theSign"].ToString();
}
}
a C# beginner here. I've been following a guide on making a simple calculator. Everything worked fine 'till I added the point button. If I use the calculator to calculate basic integers there's no problem. However, when I add in the point button to calculate doubles with a decimal it gets all screwed up. Any ideas?
// Above this are the numeric buttons, no problem with those
private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnPoint.Text;
}
double total1 = 0;
double total2 = 0;
private void btnPlus_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text); // Error comes here
txtDisplay.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
total2 = total1 + double.Parse(txtDisplay.Text); // And one time it came here
txtDisplay.Text = total2.ToString();
total1 = 0;
}
Time ago I've made a simple calculator and for checking the input I have used regex(if you don't know what is a Regex take a look here
You can use this regex for checking the input: ^[0-9]{0,}([.,][0-9]{1,})?$
It allows:
0
10
100
1,2
1.2
But not
.1
,1
And all type of string
For using the regex in c# you must declare a Regex object. Before that you need to add using System.Text.RegularExpressions;
Than use the regex is quite simple
Regex regex=new Regex(pattern);
if(regex.IsMatch(myTextBox.Text))
{//Do something
}
else{//Catch the error
}
If you want know more about regular expression take a look here
Instead of using Double.Parse use Double.TryParse.
private void btnPlus_Click(object sender, EventArgs e)
{
Double v = 0;
if ( Double.TryParse(txtDisplay.Text.Trim(), out v)
{
total1 = total1 + v;
txtDisplay.Clear();
}
else
{
// Invalid value
}
}
I am new to c# , i have read few basic concepts and now want to learn actual programming , thats why i started out with simple Calculator program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double num1 = 0;
double num2 = 0;
private void one_Click(object sender, EventArgs e)
{
textBox1.Text =textBox1.Text+one.Text;
}
private void clear_Click(object sender, EventArgs e)
{
textBox1.Clear();
// textBox1.Text = " ";
}
private void two_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+two.Text;
}
private void three_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+three.Text;
}
private void four_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+four.Text;
}
private void five_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + five.Text;
}
private void six_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + six.Text;
}
private void seven_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + seven.Text;
}
private void eight_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + eight.Text;
}
private void nine_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + nine.Text;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void add_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(textBox1.Text) ;
textBox1.Clear();
}
private void ten_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + ten.Text;
}
private void equal_Click(object sender, EventArgs e)
{
num2 = num1 + double.Parse(textBox1.Text) ;
textBox1.Text = num2.ToString();
num1 = 0;
}
}
}
This code is given in the book and they said its working .Actual problem is it works ONLY some times and some times it gives error as " Input string was not in a correct format "
What is the solution .
My second question is -- is this right approach to learn any programming language ? or should i just continue reading some more stuff n programs ?
If some one can help me with websites containing sample programs it will be very helpful .
Your problem is parsing the double. The Parse function cannot parse a string that does not represent a double.
Consider the string "135.42", this could easily be parsed to the double value 135.42. But what if the string was "Abc#%%#". This does not represent a double value and that is where you are getting your exception.
If this is your first programming language, you should read a introductory book to C# as a new programmer.
If double.Parse can't parse the string into a double then an exception is thrown. However, it's often better to use double.TryParse as it will simply return false instead of throwing an exception.
double tmp;
if(double.TryParse(textBox1.Text, out tmp))
{
num2 = num1 + tmp;
textBox1.Text = num2.ToString();
num1 = 0;
}
else
{
//double could not be parsed from textbox
}
You need to restrict the user to input only numbers in your textbox. You can do it by using keydown event of textbox. Where you will check if inputed char was numeric, only then keep it in the textbox. Here is the solution of your problem. Have a look at this:
How do I make a textbox that only accepts numbers?
For learning C#, i would prefer:
C# 5.0 in a Nutshell: The Definitive Reference
Before you do double.Parse() you should verify the user input, i.e. That it is an actual number.
I would suggest using TryParse method instead, as such:
double num;
bool isNum = double.TryParse(Str, out num);
if (isNum)
{
//Calculate here
}
If you wanted to handle invalid arguments more gracefully you could use Double.TryParse instead.
Here is the magic: double.Parse(textBox1.Text)
This function accepts only numbers (with comma or dot depends on your culture) in the string. If you pass anything else you will receive the given exception. Validate the input before you parse it or Use TryParse
double valueinDouble;
var success = double.TryParse(textBox1.Text), out valueinDouble)
if (success)
{
// do the calculation here
}
The TryParse has another implementation where you can specify the culture.
var success = double.TryParse(textBox1.Text), NumberStyles.Any, new CultureInfo("en-US"), out valueinDouble)