2010-09-08 67 views
0

大部分情況下,問題是安德烈和布列塔尼彈出消息框,但它對Eric正常工作。如果我試圖在每條if語句之後放入else語句,它仍然會在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"); 
     } 

     { 




     } 

    } 

回答

1
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"); 
} 
+0

+1,但實際上我們正在重複自己。希望我們可以進一步減少它。 – 2010-09-09 00:56:59

2

嘗試使用其他如果這樣。

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"); 
} 
2

試試這個...通過保持名稱的列表,你可以很容易地擴展覆蓋的名稱,而不必編寫任何代碼。只需將新的名稱添加到名稱列表

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"); 
} 
+0

這個效果最好。我還有一個問題,while循環看起來像是在完成同樣的任務。 – user770022 2010-09-08 23:13:21

+0

做什麼?這取決於你想要完成的事情。 – 2010-09-09 03:07:52

0

好了,我不知道你剛纔的嘗試,但因爲它代表目前各if語句被另案處理。所以如果textBox1.Text!=「Eric」,則附加到Eric的其他人將會觸發,並且在這種情況下顯示MessageBox,而不管其他兩個if是否匹配。

也許您在嘗試其他方法時遇到錯誤?試試上面的一些人如何發佈,看看是否有效。