I am a complete newb when it comes to c# and have been struggling for the past 4 hours trying to create a method instead of using multiple if/else statements. Can anybody point me in the write direction?
Basically the following code has 5 inputs that will calculate their square root when button1 is clicked.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace sqRoot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void gatherTextBoxData()
{
double[] _lookup = new double[5];
double doubleUserInput1;
double doubleUserInput2;
double doubleUserInput3;
double doubleUserInput4;
double doubleUserInput5;
if (Double.TryParse(textBox1.Text, out doubleUserInput1))
{
double doubleUserSqRoot1 = Math.Sqrt(doubleUserInput1);
label2.Text = Convert.ToString(doubleUserSqRoot1);
}
else
{
label2.Text = textBox1.Text + " is not a number";
}
if (Double.TryParse(textBox2.Text, out doubleUserInput2))
{
double doubleUserSqRoot2 = Math.Sqrt(doubleUserInput2);
label3.Text = Convert.ToString(doubleUserSqRoot2);
}
else
{
label3.Text = textBox2.Text + " is not a number";
}
if (Double.TryParse(textBox3.Text, out doubleUserInput3))
{
double doubleUserSqRoot3 = Math.Sqrt(doubleUserInput3);
label4.Text = Convert.ToString(doubleUserSqRoot3);
}
else
{
label4.Text = textBox3.Text + " is not a number";
}
if (Double.TryParse(textBox4.Text, out doubleUserInput4))
{
double doubleUserSqRoot4 = Math.Sqrt(doubleUserInput4);
label5.Text = Convert.ToString(doubleUserSqRoot4);
}
else
{
label5.Text = textBox4.Text + " is not a number";
}
if (Double.TryParse(textBox5.Text, out doubleUserInput5))
{
double doubleUserSqRoot5 = Math.Sqrt(doubleUserInput5);
label6.Text = Convert.ToString(doubleUserSqRoot5);
}
else
{
label6.Text = textBox4.Text + " is not a number";
}
}
private void button1_Click(object sender, EventArgs e)
{
gatherTextBoxData();
}
}
}