如果使用单选按钮,如何使用else [英] How to use else if with radio buttons

查看:91
本文介绍了如果使用单选按钮,如何使用else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码到目前为止,在选择 ADD 单选按钮并单击计算按钮时使用两个文本框计算数字。



This my code so far to calculate numbers using two textboxes upon choosing ADD radio button and clicking on Calculate button.

 private void btnCalculate_Click(object sender, EventArgs e)
        {
            //try

            //{

            //Local  variables
            double dFirstNumber; // To hold FirstNumber
            double dSecondNumber; // To hold SecondNumber
            double dResult; // To Hold Result


            // Validate First Number  using double.TryParse 

            if (double.TryParse(txtFirstNumber.Text, out dFirstNumber))


            //Validate second number using double.TryParse 
            {
                if (double.TryParse(txtSecondNumber.Text, out dSecondNumber))


                    // Validate Result  using double.TryParse 
                {
                    if (double.TryParse(txtResult.Text, out dResult))
                    {


                        // do addition when  Add radio button is chosen
                        //and calculate button is clicked

                        if (radAdd.Checked)

                            //Add First and second Number
                         
                           dResult = dFirstNumber + dSecondNumber;
                    }

                    {

                        txtResult.Text = dResult.ToString("n1");
                    }
                }
            }
        }
    }
}







如何为减去(radSubtract),乘(radmultiply)和除(raddivide)单选按钮添加 代码使用else if?



另外,尝试使用 try-catch 块进行检查。如果第一个和第二个文本框输入了 没有输入数字并且单击了计算按钮然后抛出第一个数字无效的异常。



如果第一个框已输入数字但是 第二个没有输入数字然后抛出第二个数字是无效'。



文本框有数字 时也抛出异常单击计算按钮后,选中 无单选按钮。例外应该说请选择其中一个单选按钮。



感谢您的时间




How can I add code for subtract(radSubtract), multiply(radmultiply) and divide(raddivide) radio buttons using else if?

Also, trying to use try-catch block to check. If First and second textboxes have NO number entered and Calculate button is clicked then throw exception that says 'First Number is not valid'.

If First box has number entered BUT Second one has no number entered then throw exception that says 'Second Number is not valid'.

And also throw exception when text boxes have numbers BUT no radio button is checked after Calculate button is clicked. Exception should say "please choose one of the radio buttons."

Thank you for your time

推荐答案

我认为嵌套if语句的结构是你的第一个问题。

验证第一个数字

验证第二个数字

(没有因为你要覆盖它而验证结果的原因!)

然后根据单选按钮计算结果。 (这里可能有错误!例如除以零或溢出)

报告结果。



异常可能不是你想要的错误处理,因为从按钮单击处理程序,方法之外没有抓住异常的好地方。相反,添加一个多行标签或只读TextBox控件来显示任何错误消息。



不完整的代码,但类似于:

I think your structure of the nested if statements is your first problem.
Validate the first number
Validate the second number
(There's no reason to validate the result since you're about to overwrite it!)
Then calculate the result based on the radio buttons. (There could be errors here! e.g. divide by zero or overflow)
Report result.

An exception is probably not what you want for the error handling, since from a button click handler, there's no good place outside the method to catch the exception. Instead, add a multiline Label or readonly TextBox control to display any error messages.

Not complete code, but something like:
private const string BadFirstNumber = "Bad first number"; // better wording is up to you!
private const string BadSecondNumber = "Bad second number";
private const string DivisionByZero = "Division by zero";
private const string NoOperationSelected = "No operation selected";
private const string NewLine = "\n";

private void btnCalculate_Click(object sender, EventArgs e)
{
  //Local  variables
  double dFirstNumber; // To hold FirstNumber
  double dSecondNumber; // To hold SecondNumber
  double dResult; // To Hold Result
  List<string> messages = new List<string>();
  bool success = true;  // assume all will go well
 
  // Validate First Number  using double.TryParse 
  if (!double.TryParse(txtFirstNumber.Text, out dFirstNumber))
  {
    messages.Add(BadFirstNumber);
    success = false;
  }

  // It's probably a good idea to validate both input values
  //Validate second number using double.TryParse 
  if (!double.TryParse(txtSecondNumber.Text, out dSecondNumber))
  {
    messages.Add(BadSecondNumber);
  } 


  if (success)
  {
    try
    {
      if (radAdd.Checked)
        dResult = dFirstNumber + dSecondNumber;
      else if (radSubtract.Checked)
        dResult = dFirstNumber - dSecondNumber;
      else if (...)
        // etc.
      else
      {
        messages.Add(NoOperationSelected);
        success = false;
      }
    }
    catch (DivideByZeroException)
    {
      messages.Add(DivisionByZero);
    }
    catch (OverflowException)
    {
      messages.Add(ArithmeticOverflow);
    }
 
    if (success)
    {
      txtResult.Text = dResult.ToString("n1");
      messages.Add(SuccessfulResult);
    }
    lblMessages.Text = string.Join(NewLine, messages);
  }
}



还有其他设计会更好,但这是一个良好的开端,与你的起点并没有太大差别。


There are other designs that would be better but this is a good start and not too different from where you are starting.


首先,使用RadioButtons的重点是,其中一个,只有一个将被检查。



假设你有四个RadioButtons,'rbAdd,'rbSubtract ......等等。选择它们并为它们分配相同的'CheckChanged EventHandler;那么:
First, the whole point of using RadioButtons is that one, and only one, of them is going to be "checked" at all times.

Let's assume you have four RadioButtons, 'rbAdd, 'rbSubtract ... etc. Select them and assign the same 'CheckChanged EventHandler to all of them; then:
// this is not executable code; it is a sketch for executable code

private RadioButton selectedRadioButton;

private void AllRadioButtons_CheckedChanged(object sender, EventArgs e)
{
    var thisRB = sender as RadioButton;

    if (thisRB.Checked) selectedRadioButton = thisRB;
}

现在,在你的'计算方法:

Now, in your 'calculate method:

// this is not executable code; it is a sketch for executable code

private void btnCalculate_Click(object sender, EventArgs e)
{
    // validate the content of the two TextBoxes
    // if not valid: clear TextBoxes and exit ?
    // throw error ?

    // int n1 = validate TextBox1
    // int n2 = validate TextBox2

    int result;

    switch (selectedRadioButton.Name)
    {
        case "rbAdd":
            result = n1 + n2;
            break;

        case "rbSubtract":
            break;

        default:
            break;
    }

    // write the 'result into a TextBox
}


if(radio_add.SelectedItem.Text ==Add)

{

//添加功能

}

else if(radio_sub.SelectedItem.Text ==Sub)

{

//减法功能

}

其他

{

//警告信息(请选择方法

}
if(radio_add.SelectedItem.Text=="Add")
{
// function for addition
}
else if(radio_sub.SelectedItem.Text=="Sub")
{
// function for substraction
}
else
{
//Alert Message(please select an method
}


这篇关于如果使用单选按钮,如何使用else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆