我在考虑下面一段代码中的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#!
答案 0 :(得分:5)
您应该在方法开头用isFound
声明并初始化false
:
public void searchGlossary(String word)
{
var isFound = false;
StringBuilder description = new StringBuilder(512);
...
}
答案 1 :(得分:0)
我需要的是检查是否找到了所需的单词,如果不是,我想显示错误对话,所以这是我的解决方案:
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);
}
在这里,我自己找到了这个解决方案!