简体   繁体   English

C#控制台应用程序在while循环中显示无效输入

[英]C# Console Application display invalid input in while loop

I have this C# console application code here that reads text from a file. 我这里有此C#控制台应用程序代码,可从文件中读取文本。 when a user inputs a value, it searches the file for lines that contain that value. 当用户输入一个值时,它将在文件中搜索包含该值的行。 In my case, the console will ask for a room number, the console will then search room.txt for the room number thats split with ',' 在我的情况下,控制台将询问房间号,然后控制台将在room.txt中搜索以“,”分隔的房间号

class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        string line;
        string roomNumber;

        Console.WriteLine("Enter room number");
        roomNumber = Console.ReadLine();
        // Read the file and display it line by line.             
        System.IO.StreamReader file = new 
              System.IO.StreamReader("room.txt");
        while ((line = file.ReadLine()) != null)
        {
            string[] words = line.Split(',');
            if (roomNumber == words[1])
            {                 
                Console.WriteLine(line);
            }             
                counter++;
        } 

        file.Close();

        // Suspend the screen.             
         Console.ReadLine(); 
        }
    }
}

How do i make it so that it will write "Invalid room number" when it cant find it in the text file, and then loop back to asking the room number. 我如何使它在文本文件中找不到它时会写“ Invalid room number”,然后循环返回以询问房号。

I would read the entire file at once, construct an enumerable from it and try to find the first match: 我会立即读取整个文件,从中构造一个可枚举的对象,然后尝试找到第一个匹配项:

bool found = false;

do
{
    Console.WriteLine("Enter room number");
    string roomNumber = Console.ReadLine();

    using (StreamReader file = new StreamReader("room.txt"))
    {
        string str = file.ReadToEnd();
        string[] rooms = str.Split(new char[] { '\r', '\n', ',' }, StringSplitOptions.RemoveEmptyEntries);

        if (!rooms.Any(room => room == roomNumber))
        {
            Console.WriteLine("Invalid room");
        }
        else
        {
            Console.WriteLine($"Found room {roomNumber}");
            found = true;
        }
    }
}
while (!found);

This code uses LINQ to find the first match ( Any ) on your input array. 此代码使用LINQ查找输入数组上的第一个匹配项( Any )。 Then it will display a message if it has found the room or not. 然后,如果没有找到房间,它将显示一条消息。 Also note the using , which makes your file stream close nicely, even when an exception occurs. 还要注意using ,即使发生异常,它也可以使文件流很好地关闭。

If you want to keep your current code, you can just use a do while loop which will check a boolean specifying if you found a line or not, and exit the loop only when a value is found. 如果要保留当前代码,则可以使用do while循环,该循环将检查一个布尔值,指定是否找到行,并仅在找到值时退出循环。

class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        bool lineFound = false;
        string line;
        string roomNumber;

        do
        {
            Console.WriteLine("Enter room number");
            roomNumber = Console.ReadLine();
            // Read the file and display it line by line.             
            using (StreamReader file = new StreamReader("room.txt"))
            {
                while ((line = file.ReadLine()) != null)
                {
                    string[] words = line.Split(',');
                    if (roomNumber == words[1])
                    {                 
                        Console.WriteLine(line);
                        lineFound = true;
                    }             
                        counter++;
                } 

                if(!lineFound)
                {
                    Console.WriteLine("Invalid room number");
                }
            }

        } while(!lineFound);

        // Suspend the screen.             
         Console.ReadLine(); 
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM