簡體   English   中英

代碼在if語句中不起作用

[英]code not working inside if statement

我在考慮以下代碼中的if / else語句時遇到問題。 實際上,我想告訴用戶是否未找到文件中的單詞,我的代碼必須顯示錯誤消息,否則我的代碼必須顯示新的表單,這是我的代碼:

    public void searchGlossary(String word)
    {
        StringBuilder description = new StringBuilder(512);
        string descLine;
        using (StreamReader reader = File.OpenText("C:/Users/--- /Desktop/--- .txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (line.StartsWith(word, StringComparison.OrdinalIgnoreCase))
                {
                    // At this point we've already read the keyword and it matches our input

                    // Here we start reading description lines after the keyword.
                    // Because every keyword with description is separated by blank line
                    // we continue reading the file until, the last read line is empty 
                    // (separator between keywords) or its null (eof)
                    while ((descLine = reader.ReadLine()) != string.Empty && descLine != null)
                    {
                        description.AppendLine(descLine);
                    }
                    //descbox.Text = description.ToString();
                    isfound = true;
                    DomainExpertForm form = new DomainExpertForm(keyword, description.ToString());
                    form.Show();
                    break;
                }

            }

            if (isfound == false)
            {
                MessageBox.Show("No Matches found for Word " + word, "Domain Expert Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }


    }

問題是,如果找不到該單詞,它將始終顯示表單,而不顯示錯誤消息。 有什么問題,解決方案可以幫助我我是新的C#!

您應該在方法開始時用false聲明並初始化isFound

public void searchGlossary(String word)
{
  var isFound = false; 
  StringBuilder description = new StringBuilder(512);

  ...
}

我需要的是檢查是否找到了所需的單詞,否則,我想顯示錯誤對話,所以這是我的解決方案:

    I simply checked the length of the found string; if its ==0 i show up an error message as:

        if (description.ToString().Length==0)
        {
            MessageBox.Show("No Matches found for Word " + word, "Domain Expert Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

然后我自己找到了這個解決方案!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM