我有一个短语输入到与此类似的文本框中:“明天天气里有什么天气”
目前,此代码将郊区字符串设置为大写名称,并将 suburbID 设置为值。
public void requestedSuburb(String suburbFromForm1)
{
suburb = suburbFromForm1;
if (suburb.Contains("taree"))
{
suburb = "Taree";
suburbID = "zmw:00000.1.95784.xml";
}
else if (suburb.Contains("port macquarie"))
{
suburb = "Port Macquarie";
suburbID = "zmw:00000.1.94787.xml";
}
(在此点之下,使用 else if 语句检查更多郊区名称。
将整个InputTextbox.Text传递到郊区字符串以检查上述内容。
我的问题是,是否有 else if 语句可以检查郊区字符串,如果没有找到郊区文本,它可以默认选择? (即:我希望'Taree'成为默认设置。)
我现在拥有的是这个,但它没有返回任何东西:
else if (!suburb.Contains("taree") || (!suburb.Contains("port macquarie")))
{
suburb = "Port Macquarie"
suburbID = "zmw:00000.1.94787.xml";
}
答案 0 :(得分:6)
您只需在所有else
的末尾else-if
,就像这样:
if (suburb.Contains("taree"))
{
suburb = "Taree";
suburbID = "zmw:00000.1.95784.xml";
}
else if (suburb.Contains("port macquarie"))
{
suburb = "Port Macquarie";
suburbID = "zmw:00000.1.94787.xml";
}
else {
suburb = "default";
}
答案 1 :(得分:1)
您只想要else
:
if (suburb.Contains("taree"))
{
suburb = "Taree";
suburbID = "zmw:00000.1.95784.xml";
}
else if (suburb.Contains("port macquarie"))
{
suburb = "Port Macquarie";
suburbID = "zmw:00000.1.94787.xml";
}
else
{
// this fires if nothing else above is correct
suburb = "Taree";
suburbID = "zmw:00000.1.95784.xml";
}
答案 2 :(得分:1)
使用else
处理默认设置,如下所示:
if (suburb.Contains("taree"))
{
suburb = "Taree";
suburbID = "zmw:00000.1.95784.xml";
}
else if (suburb.Contains("port macquarie"))
{
suburb = "Port Macquarie";
suburbID = "zmw:00000.1.94787.xml";
}
else
{
suburb = "Taree";
suburbID = "zmw:00000.1.95784.xml";
}
您也可以将默认设置指定为开头,然后仅在找到匹配项时覆盖默认值,如下所示:
// Default values
suburb = "Taree";
suburbID = "zmw:00000.1.95784.xml";
if (suburb.Contains("port macquarie")
{
suburb = "Port Macquarie";
suburbID = "zmw:00000.1.94787.xml";
}
注意:对于您发布的示例代码,这会将您的逻辑简化为单个
if
。这也消除了第一个if
和else
中的重复逻辑。