搜索数字时始终将第一个值设为false?

时间:2017-11-22 08:18:25

标签: c# type-conversion

我要做的是允许用户搜索在false Vektor中保存了多少truebool值。程序应该处理输入也很重要错误。

我想我必须使用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();
    }
}

2 个答案:

答案 0 :(得分:4)

要在数组中搜索某种数据类型的值,您需要将用户输入转换为该数据类型。然后继续比较转换后的值,就像现在一样。

转换可以通过以下方式完成:

Console.Write("Skriv in sökOrd: [TRUE|FALSE]");
string searchWord = Console.ReadLine();
bool search = Convert.ToBoolean(searchWord);

bool foundAnyMatches = false


for (int i = 0; i < boolVektor.Length; i++)
{
    if (boolVektor[i] == search)
    {
        Console.WriteLine("The following were found: " + boolVektor[i] + 
        "Index: " + i);
        foundAnyMatches = true;
    }
}
if (!foundAnyMatches)
{
    Console.WriteLine("Your search failed");
}

请不要更改search值!因为你用它作为搜索条件!

修改

对于错误输入的处理,您可以将转换放入https://www.kernel.org/doc/Documentation/arm/mem_alignment块,也可以使用try/catch方法

答案 1 :(得分:3)

我让您当前的方法有效并在评论中解释了一些内容:

Random newRandom = new Random();
int slumpTal = newRandom.Next( 1, 101 );
bool[] boolVektor = new bool[ slumpTal ];

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( "True/False: " );
bool search = Convert.ToBoolean(Console.ReadLine()); //Thanks Mong Zhu
bool foundMatches = false;

for ( int i = 0; i < boolVektor.Length; i++ )
{
    if ( boolVektor[ i ] == search )
    {
        //If you do boolVektor[i] it will just show true/false
        Console.WriteLine( $"The following index is found: {i} " );
        foundMatches = true;
    } 
}
if ( !foundMatches ) //We check if the search failed here because now the search is finished
{
    Console.WriteLine( "Your search failed" );
}
Console.ReadLine();

如果您想计算用户输入的出现次数,请用此替换for循环:

int count = boolVektor.Where( row => row == search ).Count();
if(count != 0)
{
    Console.WriteLine( $"{count} items were found" );
}
else
{
    Console.WriteLine( "Your search failed" );
}
Console.ReadLine();