繁体   English   中英

错误检查问题

[英]Error checking problem

在大多数情况下,这确实有效,但问题是弹出消息框显示Andrea和Brittany,但它对于Eric正常工作。 如果我尝试将else语句放在每个if语句之后,那么它仍然会在Brittany和Andrea上弹出,然后在Eric上也会弹出。 有人可以告诉我我在做什么错。

    private void button1_Click(object sender, EventArgs e)
    {
        String Andrea;
        String Brittany;
        String Eric;
        if (textBox1.Text == "Andrea")
        {     
            Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
        }

        if (textBox1.Text == "Brittany")
        {
            Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
        }


        if (textBox1.Text == "Eric")
        {
            Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
        }
        else
        {
            MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
        }   

        {




        } 

    }

如果这样,请尝试使用else。

if (textBox1.Text == "Andrea")
{     
    Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else if (textBox1.Text == "Brittany")
{
    Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else if (textBox1.Text == "Eric")
{
    Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else
{
    MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
} 

尝试此操作...通过保留名称列表,您可以轻松扩展涵盖的名称,而不必编写任何其他代码。 只需将新名称添加到名称列表

List<string> names = new List<string>() // list of names to check for
{                                       // if a name is not in this list
   "Andrea","Brittany","Eric"           // the error message will show
};                                      // otherwise, the calculation will be performed

if ( names.Contains(TextBox1.Text) )
{
    Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else
{
    MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}
switch(textBox1.Text)
{
    case "Andrea" : Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
    case "Brittany" : Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
    case "Eric" : Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
    default: MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}

好吧,我不知道您之前的尝试,但是就目前而言,每个if语句都是分开处理的。 因此,如果textBox1.Text!=“ Eric”,则附加到Eric的else将被触发,在这种情况下,将显示MessageBox,而不管其他两个if是否匹配。

如果尝试尝试,也许您在其他方面有错误? 尝试上述人员的发布方式,看看是否可行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM