2012-04-15 61 views
0

我搞錯了某種字典,即應該將單詞從一個文本框轉換爲另一個文本框,而其他方式,但它並不像我我喜歡它。該按鈕的代碼是:即使「if」爲真,「else」也會完成

private void button1_Click(object sender, EventArgs e) 
    { 
     string[] lines = File.ReadAllLines("C:/words.txt"); 
     int i = 0; 
     var items = from line in lines 
        where i++ != 0 
        let words = line.Split('|') 
        where words.Count() > 1 
        select new 
        { 
         word = words[0], 
         translation = words[1] 
        }; 

     foreach (var item in items) 
     { 
      if (textBox1.Text == item.word) 
      { 
       textBox2.Text = item.translation; 
      } 
      if (textBox2.Text == item.translation) 
      { 
       textBox1.Text = item.word; 
      } 
      else 
      { 
       label3.Text = ("not found"); 
      } 
     } 
    } 

編輯:不適用於「else if」。

+0

你應該用你正在使用的語言標記你的問題。 – assylias 2012-04-15 12:54:00

+0

歡迎來到SO。如果您說明您使用哪種語言,這將有所幫助。標籤「split」和「translate」似乎不適合。 – dgw 2012-04-15 12:56:06

回答

0

我覺得最好避免if語句在可能的地方,而且我特別試圖避免別的,否則如果。其原因是,當有多種條件需要嘗試和遵循時,它就會變得令人困惑。這可能是一種更清晰的方式來了解正在發生的事情並解決您的問題。

 foreach (var item in items) 
     { 
      if (textBox1.Text == item.word) 
      { 
       textBox2.Text = item.translation; 
       continue; // Don't process anything else in this loop. 
      } 
      if (textBox2.Text == item.translation) 
      { 
       textBox1.Text = item.word; 
       continue; // Don't process anything else in this loop. 
      } 
      label3.Text = ("not found"); 
     } 

因爲我們不希望任何其他邏輯來執行(我的假設)如果我們的if語句是真實的,我們只需使用繼續跳過邏輯的其餘部分在foreach並移動到一個下一個項目。

爲什麼在循環中呢?第一次迭代中的文本是否會被後續迭代覆蓋?

+0

我應該如何讓它不作爲循環?它仍然不起作用。 – 2012-04-15 13:42:55

+0

@MátéBurján什麼不行?你總是看到「找不到?」這可能是因爲,在這種情況下,您將始終分析項目中的最後一個項目,因此可能總是觸及「未找到」狀態。如果你想在發現命中後停止,用* break *語句替換* continue *語句。這樣的循環沒有多大意義,這可能是你的主要問題。 – 2012-04-15 13:49:02

+0

是的,即使它找到了翻譯,它總是會寫入「未找到」。我也嘗試過「休息」,也沒有效果。我應該讓它停在最後一行嗎? – 2012-04-15 13:54:05

6

你需要一個else if,否則其他人只能從第二,如果發生了:

if (textBox1.Text == item.word) 
    { 
    textBox2.Text = item.translation; 
    } 
    else if (textBox2.Text == item.translation) 
    { 
    textBox1.Text = item.word; 
    } 
    else 
    { 
    label3.Text = ("not found"); 
    } 
+2

不應該是'else if'而不是'elseif'嗎? – gdoron 2012-04-15 12:59:18

+0

對不起,不是C#程序員哈哈。但是,是的,你是對的。 – Menztrual 2012-04-15 13:00:03

+0

我已經嘗試過,但它仍然寫它。 – 2012-04-15 13:03:37

1

嘗試使用else if (textBox2.Text == item.translation)而不是if (textBox2.Text == item.translation)

ELSE IF

0

從我所能看到的是,沒有其他的,如果第二如果只有第一如果是真的時纔會有效。試試這個:

foreach (var item in items) 
    { 
     if (textBox1.Text = item.word) 
     { 
      textBox2.Text = item.translation; 
     } 

     else if (textBox2.Text = item.translation) 
     { 
      textBox1.Text = item.word; 
     } 
     else 
     { 
      label3.Text = ("not found"); 
     } 
    } 
相關問題