Sam*_*aab 5 c# type-conversion
我想要做的是允许用户搜索在Vektor中保存了多少false或true值bool。程序应该处理输入错误也很重要。
我想我必须使用,Convert.Boolean但我不知道如何使用。目前,无论我搜索数字还是字母,我都会得到同样的结果。
static void Main(string[] args)
{
Random newRandom = new Random();
int slumpTal = newRandom.Next(1, 101);
bool[] boolVektor = new bool[slumpTal];
//var nacas = Convert.ToBoolean(Convert.ToInt32("0"));
for (int i = 0; i < boolVektor.Length; i++)
{
int slump = newRandom.Next(0, 2);
if (slump == 0)
boolVektor[i] = true;
else
boolVektor[i] = false;
}
{
Console.Write("Skriv in sökOrd: ");
string searchWord = Console.ReadLine();
bool search = false;
for (int i = 0; i < boolVektor.Length; i++)
{
if (boolVektor[i] == search)
{
Console.WriteLine("The following were found: " + boolVektor[i]);
search = true;
}
if (!search)
{
Console.WriteLine("Your search failed");
}
}
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
要在数组中搜索某种数据类型的值,您需要将用户输入转换为该数据类型。然后您继续以与现在相同的方式比较转换后的值。
\n\n可以通过以下方式完成转换:
\n\nConsole.Write("Skriv in s\xc3\xb6kOrd: [TRUE|FALSE]");\nstring searchWord = Console.ReadLine();\nbool search = Convert.ToBoolean(searchWord);\n\nbool foundAnyMatches = false\n\n\nfor (int i = 0; i < boolVektor.Length; i++)\n{\n if (boolVektor[i] == search)\n {\n Console.WriteLine("The following were found: " + boolVektor[i] + \n "Index: " + i);\n foundAnyMatches = true;\n }\n}\nif (!foundAnyMatches)\n{\n Console.WriteLine("Your search failed");\n}\nRun Code Online (Sandbox Code Playgroud)\n\n并且请不要更改该search值!因为你用它作为搜索条件!
编辑:
\n\n至于错误输入的处理,您可以将转换放入try/catch块中,也可以使用Boolean.TryParse()方法
\n