'else if' cant use variable from TryParse - c#

double x;
double y;
string strx = TextBoxX.Text;
string stry = TextBoxY.Text;
if (!double.tryParse(strx, out double a))
{MessageBox.Show("Incorrect input");}
else if (!double.tryParse(stry, out double b))
{MessageBox.Show("Incorrect input");}
x = a;
y = b; <---
The problem is that x and receive value of a, but y cant do the same for b.
I understand its because its within 'else' and might not get executed, but if I remove the else, then if both textboxes are empty or not numbers I'll get two error popups...
Any help resolving the issue?

You should question how your logic is set.
Right now, if either or both textboxes are wrong, the user sees the ambiguous "Incorrect input". I would find this frustrating. Where's the incorrect input? Is it the first text box? The second? Both?
As you develop better UIs, the answer will be to validate each text box and have each one that is wrong turn a color or provide some other feedback on the form itself. Otherwise, imagine how ugly the logic will get when you're presenting a form to the user with 20 different fields.
However, if you're only going to use two fields, and you want to have some logic, try something like this (note that in doing this, I got rid of the else, as well, so b will always be set):
double x;
double y;
string strx = TextBoxX.Text;
string stry = TextBoxY.Text;
List<string>() invalids = new List<string>();
if (!double.tryParse(strx, out double a))
{invalids.Add("boxX");}
if (!double.tryParse(stry, out double b))
{invalids.Add("boxY")}
if invalids.Length != 0
{MessageBox.Show("Incorrect inputs in " + String.Join(", ", invalids.ToArray());}
x = a;
y = b;
The user will enjoy a single box that tells them of all the errors more than multiple pop-up boxes, or having to hit OK each time and see that there are more errors.

if (!double.TryParse(strx, out double a) || !double.TryParse(stry, out double b))
{
MessageBox.Show("Incorrect input");
return;
}

Related

Error in calculation Winforms C#

I am building C# WinForms application which has 3 textboxes. First two take value and after calculation show value in third textbox. It has to be in textbox so user can change value if thinks that calculation is wrong. Everything works perfect, but when I run app on windows 7 I get huge error, it calculates that (for example ) 2 times 2.15 is 430. Why is that happening ? I tried installing latest .Net framework on that computer but still doesn't work and after research I have no further ideas.
num1 = num2 = sum = 0;
if (tbNum1.Text.Contains(","))
{
tbNum1.Text = tbNum1.Text.Replace(",", ".");
}
double.TryParse(tbNum1.Text, out num1);
if (tbNum2.Text.Contains(","))
{
tbNum2.Text = tbNum2.Text.Replace(",", ".");
}
double.TryParse(tbNum2.Text, out num2);
sum = num1 * num2;
sum = Math.Round(sum, 2);
tbSum.Text = sum.ToString();
Also, additional two problems appear with displaying WinForm.
First is that panels have different sizes and positions than I programatically set.
Secont is that ( and I suppose that is my fault because I am probably doing that wrong ) all panels show very slow. What I have is like 6 panels with particular dimensions and 6 buttons. Depending on pressed button, I set all panels visible to false and only correct panel visible to true. But it loads very slow. Do you have any suggestions ? Thanks a lot in advance !
Your parse to a double is wrong. You can do it like this:
double num1, num2, product = 0;
if (tb1.Text.IndexOf(",") != -1)
{
tb1.Text = tb1.Text.Replace(",", ".");
}
num1 = double.Parse(tb1.Text, System.Globalization.CultureInfo.InvariantCulture);
if(tb2.Text.IndexOf(",") != -1)
{
tb2.Text = tb2.Text.Replace(",", ".");
}
num2 = double.Parse(tb2.Text, System.Globalization.CultureInfo.InvariantCulture);
product = Math.Round(num1 * num2,2);
tb3.Text = product.ToString();
The character that double.Parse recognizes as the decimal separator depends on the supplied IFormatProvider; if you don't supply any, that's the one for the current culture.
If you specifically want to use the dot as the decimal separator, you can just use CultureInfo.InvariantCulture:
double.TryParse(tbNum2.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out double num);

Celsius to Fahrenheit Conversion Form

I am trying to create a form that will convert Celsius to Fahrenheit and vice versa, but I am running into an error with the Conversion buttons code. The problem I am getting is that the variable convertedTemperature is left empty, so that should validation fail the message will be displayed via the ouput label(lblConvertedTemperature). But because of this being left blank I get the use of unassigned variable error. My question is how can I reword the processing section to not cause this error.
Double inputTemperature;// the variable that will store txtTemperatureInput for calculation
Double convertedTemperature;// the variable that will store the converted temperature
/*********************************
* INPUT *
* *******************************/
// when the user inputs a value and clicks calculate, the input must first be validated
if (Double.TryParse(txtTemperatureInput.Text, out inputTemperature) == false)
{
lblConvertedTemperature.Text = "Temperature must be a numeric value.";// message displayed in
//output label telling user their input was not accepted because it was not numeric
txtTemperatureInput.Focus();// sets the focus back onto the temperature textbox for a new entry
}
else
{
/*******************************
* PROCESSING *
*******************************/
if (optConvertToCelsius.Checked == true)// if the convert to celsius radio button is selected
// this statement will run
{
convertedTemperature = (inputTemperature - 32)*5 / 9;// the formula for converting
//Fahrenheit to Celsius
}
else if (optConvertToFahrenheit.Checked == true)// convert to fahrenheit was selected,
//meaning the convert to fahrenheit radio button was selected, so this statement will run
{
convertedTemperature = (inputTemperature * 9) / 5 + 32; ;// the formula for converting Celsius to
//Fahrenheit
}//end concatonated if
}//end if
/******************************
*OUTPUT *
******************************/
lblConvertedTemperature.Text = Math.Round(convertedTemperature, 4).ToString();// sets the converted temperature
// label to the value of convertedTemperature
}
}
}
My question is how can I reword the processing section to not cause this error.
Well, there are two situations that the compiler is concerned about:
If the input is invalid, you're already changing lblConvertedTemperature.Text anyway... so just return after you've done that. (You then don't need an else clause, which means you'll have less nesting - always nice for readability.)
Neither optConvertToCelsius nor optConvertToFahrenheit is checked. That's a situation the compiler considers, because you've got two separate conditions that you're checking. You may know it's never going to happen, of course.
For the latter, I'd suggest just removing the second condition:
if (optConvertToCelsius.Checked)
{
...
}
else
{
...
}
Note that I've removed the == true from the first condition just as a matter of style.
Now the compiler will know that if you get to this point, one of those two blocks will be executed. As both blocks assign to convertedTemperature, the variable will be definitely assigned at the end of that code.
EDIT: Just to clarify, if you have:
if (someCondition)
{
...
}
else if (someOtherCondition)
{
...
}
the compiler will not assume that one of those blocks will be executed, regardless of what the conditions are. Even if you know that exactly one condition will be true, the compiler just follows its relatively-simple rules.
You're scoping looks off. Simply move
/******************************
*OUTPUT *
******************************/
lblConvertedTemperature.Text = Math.Round(convertedTemperature, 4).ToString();// sets the converted temperature
// label to the value of convertedTemperature
To the "processing" scope.

How to prevent double decimals in a C# calculator

I'm developing a calculator in C# and I have a button that inserts a decimal point into the number. I ran into a problem where it allows the user to insert multiple decimal points into the interface, which threw everything off. I cooked up this little statement:
if ((number % 1) > 0)
{
richTextBox1.Text = richTextBox1.Text + "";
}
else
{
richTextBox1.Text = richTextBox1.Text + ".";
}
Except it doesn't do anything! Will someone please show me a way to only allow one decimal point by fixing this statement?
onButtonToInsertDecimalClick
if richTextBox1.Text.Contains(".")
return;
else
... rest of code
Wouldn't this (pseudocode) work?
Have you tried using Double.TryParse directly?
if(Double.TryParse(richTextBox1.Text, myDoubleValue) == false)
richTextBox1.Text = lastGoodValue;
else
lastGoodValue = richTextBox1.Text;
this will also, via TryParse, give your actual double variable the proper result. As long as this occurs every time richTextBox1.Text changes, the correction code should also cause the double value to remain good, since it'll trigger when Text is reverted to lastGoodValue.

Getting data from textboxes and multiply

I have:
textbox1.text == 1.4087
textbox2.text == 521.54
It's not hardcoded, I get it from JSON. Anyway, I want to multiply these two numbers.
I use this code:
double curr = 0.0;
double price = 0.0;
double multiply = 0.0;
double.TryParse(textBox1.Text, out curr);
double.TryParse(textBox2.Text, out price);
multiply = curr * price;
textBox3.Text = multiply.ToString();
I also tried with Convert.ToDouble still no luck.
I always get 0 in textBox3. Apparently the strings are not recognized as double. But they are. Any ideas? Thanks!
EDIT: From JSON:
{"high": "567.88", "last": "543.95", "timestamp": "1394987785",
I'm using this code to get what i need:
Regex expression = new Regex(#"last"":\s""(?<Identifier>[0-9]+\.[0-9]+)");
var results = expression.Matches(Cryp);
foreach (Match match in results)
{
textBox1.Text = match.Groups["Identifier"].Value;
}
Any issues here?
Try This:
double.TryParse(textBox1,NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out curr);
double.TryParse(textBox2.Text,NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out price);
multiply = curr * price;
I would assume one of the TryParse calls fails resulting in it keeping a value of 0 so regardless of what the working one is, you're going to get 0 for a result.
I just wrote up a basic ASP.NET application with three textboxes and then just pasted your code without changing anything into the event handler for a submit button. Manually typing the two numbers you provided gave the correct answer of 734.693398 in TextBox3. Your inputs must be off.

How can I read user input from the console?

I want to get a number from the user, and then multiply that number with Pi. my attempt at this is below. But a contains gibberish. For example, if I insert 22, then a contains 50. What am I doing wrong? I don't get any compiler errors.
double a,b;
a = Console.Read();
b = a * Math.PI;
Console.WriteLine(b);
I'm not sure what your problem is (since you haven't told us), but I'm guessing at
a = Console.Read();
This will only read one character from your Console.
You can change your program to this. To make it more robust, accept more than 1 char input, and validate that the input is actually a number:
double a, b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
if (double.TryParse(Console.ReadLine(), out a)) {
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
} else {
//user gave an illegal input. Handle it here.
}
a = double.Parse(Console.ReadLine());
Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.
Edit:
To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.
If you'd like to perform some sort of error checking, simply do this:
if ( double.TryParse(Console.ReadLine(), out a) ) {
Console.Writeline("Sonuç "+ a * Math.PI;);
}
else {
Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}
Thanks to Öyvind and abatischev for helping me refine my answer.
string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);
The main reason of different input/output you're facing is that Console.Read() returns char code, not a number you typed! Learn how to use MSDN.
I think there are some compiler errors.
Writeline should be WriteLine (capital 'L')
missing semicolon at the end of a line
double a, b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
a = double.Parse(Console.ReadLine());
b = a * Math.PI; // Missing colon!
Console.WriteLine("Sonuç " + b);
string str = Console.ReadLine(); //Reads a character from console
double a = double.Parse(str); //Converts str into the type double
double b = a * Math.PI; // Multiplies by PI
Console.WriteLine("{0}", b); // Writes the number to console
Console.Read() reads a string from console A SINGLE CHARACTER AT A TIME (but waits for an enter before going on. You normally use it in a while cycle). So if you write 25 + Enter, it will return the unicode value of 2 that is 50. If you redo a second Console.Read() it will return immediately with 53 (the unicode value of 5). A third and a fourth Console.Read() will return the end of line/carriage characters. A fifth will wait for new input.
Console.ReadLine() reads a string (so then you need to change the string to a double)
Sometime in the future .NET4.6
//for Double
double inputValues = double.Parse(Console.ReadLine());
//for Int
int inputValues = int.Parse(Console.ReadLine());
double a,b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
try
{
a = Convert.ToDouble(Console.ReadLine());
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
}
catch (Exception)
{
Console.WriteLine("dönüştürme hatası");
throw;
}
Console.Read() takes a character and returns the ascii value of that character.So if you want to take the symbol that was entered by the user instead of its ascii value (ex:if input is 5 then symbol = 5, ascii value is 53), you have to parse it using int.parse() but it raises a compilation error because the return value of Console.Read() is already int type. So you can get the work done by using Console.ReadLine() instead of Console.Read() as follows.
int userInput = int.parse(Console.ReadLine());
here, the output of the Console.ReadLine() would be a string containing a number such as "53".By passing it to the int.Parse() we can convert it to int type.
You're missing a semicolon: double b = a * Math.PI;

Categories