2017-06-06 33 views
0

我在這裏有這個C#控制檯應用程序代碼,用於從文件中讀取文本。 當用戶輸入一個值時,它會在文件中搜索包含該值的行。 在我的情況下,控制檯會詢問房間號,控制檯將然後搜索room.txt的房間號那與分裂「」C#控制檯應用程序在while循環中顯示無效輸入

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

我如何讓這個會寫「無效的房間號碼「,當它無法在文本文件中找到它,然後循環回問房間號碼。

+5

這看起來非常像一個家庭作業... –

回答

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

我建議在這裏使用'boolean'而不是'int'作爲計數器,因爲它更有意義。 –

+0

謝謝,這個伎倆! –

+0

我會建議你按照@Hofman的說法使用 – jamiedanq

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,即使發生異常,也會使文件流很好地關閉。

+2

任何理由downvote問題和兩個答案? –

+0

我想你錯過了他說他想回到要求顯示無效房間後的房間號碼的那一點 – jamiedanq

+1

@jamiedanq你可能是對的。更新。 –