【发布时间】:2021-06-16 05:41:47
【问题描述】:
我的任务是创建一个至少有两个匹配值的字符串列表,然后提示用户输入其中一个值,然后我要显示输入的那个值的一个或多个索引。
我似乎已经知道如何显示所需的索引,但如果输入的值不在列表中,并且当我执行 else 时,它会搞砸,我还需要声明。在这方面寻求帮助!
所以这就是我想要的,但没有 else 语句:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<string> mprovinces = new List<string> { "Nova Scotia", "New Brunswick", "Prince Edward Island", "Nova Scotia" };
Console.WriteLine("Enter one of the following maritime provinces: \nNova Scotia, \nNew Brunswick, \nPrince Edward Island\n");
string input2 = Console.ReadLine();
for (int i = 0; i < mprovinces.Count; i++)
{
bool match = mprovinces[i] == input2;
if (match)
{
Console.WriteLine(i);
}
}
}
}
但是当我添加一个 else 语句并输入一个列表中的值时,它提供的数据比我想要的要多:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<string> mprovinces = new List<string> { "Nova Scotia", "New Brunswick", "Prince Edward Island", "Nova Scotia" };
Console.WriteLine("Enter one of the following maritime provinces: \nNova Scotia, \nNew Brunswick, \nPrince Edward Island\n");
string input2 = Console.ReadLine();
for (int i = 0; i < mprovinces.Count; i++)
{
bool match = mprovinces[i] == input2;
if (match)
{
Console.WriteLine(i);
}
else
{
Console.WriteLine("Sorry, this is not in the list");
}
}
}
}
【问题讨论】:
-
数据多于您的需要是什么意思?如果要在执行 else 语句时结束循环,请使用 break;走出循环
-
这是你开始学习编程的最佳时机——学习how to step through code in the debugger。
-
对于提示,我可以建议
Console.WriteLine("Enter one of the following maritime provinces:\n" + String.Join("\n", mprovinces)); -
疯狂反思是对的!我明白了,所以我尝试了一些“else if”并试图说 (!match) 但这也不起作用,因为它每次都在经历。那么我会以某种方式将该语句放在我的循环之外吗?或者我应该使用不同的循环,比如 do/while?
-
感谢您的提示,乔尔。我已经调整了提示!
标签: c# list loops for-loop if-statement