简体   繁体   中英

C# Console Application display invalid input in while loop

I have this C# console application code here that reads text from a file. 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 ','

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.

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. 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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