[英]C# Console Application display invalid input in while loop
我這里有此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();
}
}
}
我如何使它在文本文件中找不到它時會寫“ Invalid room number”,然后循環返回以詢問房號。
我會立即讀取整個文件,從中構造一個可枚舉的對象,然后嘗試找到第一個匹配項:
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
,即使發生異常,它也可以使文件流很好地關閉。
如果要保留當前代碼,則可以使用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.