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

时间:2017-06-06 07:48:50

标签: c#

我这里有这个C#控制台应用程序代码,用于从文件中读取文本。 当用户输入值时,它会在文件中搜索包含该值的行。 在我的情况下,控制台将询问房间号,然后控制台将搜索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(); 
        }
    }
}

我如何制作它以便写入"无效的房间号码"当它无法在文本文件中找到它,然后循环回询问房间号。

2 个答案:

答案 0 :(得分:3)

我会立刻读取整个文件,从中构造一个可枚举的文件并尝试找到第一个匹配项:

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);

此代码使用LINQ查找输入数组上的第一个匹配项(Any)。然后,如果找到了房间,它将显示一条消息。另请注意using,即使发生异常,它也可以很好地关闭文件流。

答案 1 :(得分:2)

如果你想保留当前的代码,你可以使用一个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(); 
        }
    }
}