How to turn null to 0

I built a small program that calculates an average of 15 numbers or less. There are 15 text fields, each defaulting to "0". The program knows how to get the sum of all typed numbers and divide it by the number of text fields that do not return "0". But if the user mistakenly deletes one of the "0" in one of the text fields .. a runtime error.

Initially, I solved this problem by writing this “if statement” 15 times (one for each text field):

if (t1.Text == "") { tr1 = 0; } else { tr1 = Double.Parse(t1.Text); } 

this code checks to see if there is any thing in the text field (for example, with the name t1), if true, the program gives double 'tr1' (do not confuse with 't1'), value '0', if false, the code gives double 'tr1' the text is 't1'.

I had to write this “if” 15 times. I wanted to know if I can write the same code with arrays and a for loop, and how?

here is the whole code (sorry for var names not like using var.):

  private void goyouidiot_Click(object sender, EventArgs e) { double tr1; double tr2; double tr3; double tr4; double tr5; double tr6; double tr7; double tr8; double tr9; double tr10; double tr11; double tr12; double tr13; double tr14; double tr15; if (t1.Text == "") { tr1 = 0; } else { tr1 = Double.Parse(t1.Text); } if (t2.Text == "") { tr2 = 0; } else { tr2 = Double.Parse(t2.Text); } if (t3.Text == "") { tr3 = 0; } else { tr3 = Double.Parse(t3.Text); } if (t4.Text == "") { tr4 = 0; } else { tr4 = Double.Parse(t4.Text); } if (t5.Text == "") { tr5 = 0; } else { tr5 = Double.Parse(t5.Text); } if (t6.Text == "") { tr6 = 0; } else { tr6 = Double.Parse(t6.Text); } if (t7.Text == "") { tr7 = 0; } else { tr7 = Double.Parse(t7.Text); } if (t8.Text == "") { tr8 = 0; } else { tr8 = Double.Parse(t8.Text); } if (t9.Text == "") { tr9 = 0; } else { tr9 = Double.Parse(t9.Text); } if (t10.Text == "") { tr10 = 0; } else { tr10 = Double.Parse(t10.Text); } if (t11.Text == "") { tr11 = 0; } else { tr11 = Double.Parse(t11.Text); } if (t12.Text == "") { tr12 = 0; } else { tr12 = Double.Parse(t12.Text); } if (t13.Text == "") { tr13 = 0; } else { tr13 = Double.Parse(t13.Text); } if (t14.Text == "") { tr14 = 0; } else { tr14 = Double.Parse(t14.Text); } if (t15.Text == "") { tr15 = 0; } else { tr15 = Double.Parse(t15.Text); } double[] sch = { tr1, tr2, tr3, tr4, tr5, tr6, tr7, tr8, tr9, tr10, tr11, tr12, tr13, tr14, tr15 }; double total = 0; double sorf = 0; for (int i = 0; i != 14; i++) { sorf = sorf + sch[i]; if (sch[i] > 0) { total++; } } double totalic = sorf / total; string glass = totalic.ToString(); result.Text = ("your score: " + glass); } 
+6
c #
source share
7 answers
 Double.TryParse(t1.Text.Trim(), out tr1); 

sets tr1 to the numeric value of the text field, or 0.0 if for some reason he was unable to convert it. It will also return true if the conversion was successful or false if it failed, but you do not need to return a value if the default is 0.0.

Added bonus: it will not throw an exception if someone decides to put "This is not a number." in the text box. He will see the value as 0.

To do this in an array ...

 TextBox t[] = { t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15 }; double tr[] = new double[t.Length]; for (int i = 0; i < t.Length; ++i) { Double.TryParse(t[i].Text.Trim(), out tr[i]); } 

UPDATE:

Note that it is reasonable to expect that you can calculate the average number, which is 0. For this:

 TextBox t[] = { t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15 }; double tr[] = new double[t.Length]; int valid_count = 0; for (int i = 0; i < t.Length; ++i) { if (Double.TryParse(t[i].Text.Trim(), out tr[i])) ++valid_count; } 

Set the default values ​​for the text fields to "empty" (""), and then you will know how many of them were entered by user 0 and how many were empty. Divide the amount by valid_count to get the exact average. (But make sure valid_count > 0 , or you will most likely get the exception individually.)

+10
source share

Of course, create double tr[15] and the corresponding array of text fields.

Then just use:

 for (int i = 0; i < 15; i++) { if (t[i].Text == "") { tr[i] = 0; } else { tr[i] = Double.Parse(t[i].Text); } } 
+7
source share

If this is just a large amount of source code accepted with your if , you can choose something like:

 tr1 = ( t1.Text == "") ? 0 : Double.Parse( t1.Text); tr2 = ( t2.Text == "") ? 0 : Double.Parse( t2.Text); : tr15 = (t15.Text == "") ? 0 : Double.Parse(t15.Text); 

It's nice and neat, doesn't take up a lot of screen real estate, and it's pretty easy to see the intention.

Or, even better, something like:

 tr1 = 0; try { tr1 = Double.Parse( t1.Text); } catch (Exception e) {}; tr2 = 0; try { tr2 = Double.Parse( t2.Text); } catch (Exception e) {}; : tr15 = 0; try { tr15 = Double.Parse(t15.Text); } catch (Exception e) {}; 

because the fields can be invalid and not empty.

You can do the same with arrays and a for loop if you structure your data and controls in different ways, but this may not be necessary for only fifteen elements. Of course, if you added more, I would seriously consider this option.

And you can load the values ​​directly into the array so you don't need sch :

 double tr[15]; : tr[ 0] = 0; try { tr[ 0] = Double.Parse( t1.Text); } catch (Exception e) {}; tr[ 1] = 0; try { tr[ 1] = Double.Parse( t2.Text); } catch (Exception e) {}; : tr[14] = 0; try { tr[14] = Double.Parse(t15.Text); } catch (Exception e) {}; : double total = 0; double sorf = 0; for (int i = 0; i < 15; i++) { if (tr[i] > 0) { sorf = sorf + tr[i]; total++; } } : 

For a minimal code solution, you can also create an array of text fields from which you extract information. Something like (unverified):

 TextBox t[] = {t1, t2, t3, ..., t15}; double tr[t.length]; : for (int i = 0; i < t.length; i++) { tr[i] = 0; try { tr[i] = Double.Parse(t[i].Text); } catch (Exception e) {}; } : double total = 0; double sorf = 0; for (int i = 0; i < tr.length; i++) { if (tr[i] > 0) { sorf = sorf + tr[i]; total++; } } : 
+3
source share

Write a function that converts the value of the text field to double, something like:

 private static double ConvertTextboxValueToDouble(string value) { double result; Double.TryParse(value, out result); return result; } 

Then create an array of your text fields, converting their values ​​to double:

 double[] values = { ConvertTextboxValueToDouble(t1.text), ConvertTextboxValueToDouble(t2.text), ConvertTextboxValueToDouble(t3.text), ... ConvertTextboxValueToDouble(t15.text) } 
+2
source share

Have you considered using NumericUpDown instead of TextBox?

Also, instead of writing something fifteen times, you should really reorganize your code and try one of the following methods:

  • Register for all your input fields an event in which everyone uses the same code

     public void ValueChanged(Object sender, EventArgs e) { var numericUpDown = sender as NumericUpDown; if(numericUpDown == null) return; //ToDo: Put some check code here } 
  • Use multiple List<T> where you insert all your boxes and iterate over them to check all settings

     var myList = new List<NumericUpDown>(); //ToDo: Put all your boxes into it myList.Add(numericUpDown1); myList.Add(numericUpDown2); //or get the list from somewhere else myList.AddRange(this.Controls.OfType<NumericUpDown>()) //OnButtonClick foreach(var numericUpDown in myList) { //ToDo: Do some checking } 
+1
source share

Put .Trim () when retrieving values ​​from TextBox

tr3 = Double.Parse (t3.Text.Trim ());

0
source share

For these situations and thinking, in order to do the work in a small part of the code, I use a dirty little trick: put the controls in the panel.

If your panel contains only the necessary controls (in this case, text fields), this will be enough to save the values ​​in the pair list:

  private void button1_Click(object sender, EventArgs e) { List<double> doubleList = new List<double>(); foreach (TextBox t in panel1.Controls) doubleList.Add(this.checkTextBox(t)); } private double checkTextBox(TextBox t) { return (t.Text != string.Empty) ? Double.Parse(t.Text.Trim()) : 0; } 

If you cannot have a panel for text fields only and to create a command into which you have to mix the controls, you will need to perform additional validation / conversion:

  private void button1_Click(object sender, EventArgs e) { List<double> doubleList = new List<double>(); foreach (Control t in panel1.Controls) if(t is TextBox) doubleList.Add(this.checkTextBox((TextBox)t)); } private double checkTextBox(TextBox t) { return (t.Text != string.Empty) ? Double.Parse(t.Text.Trim()) : 0; } 

Hello!

0
source share

All Articles