2013-12-08 27 views
-3

爲什麼每次我有第二個if/else if聲明時,我必須輸入任何第二個if條件,兩次?幾乎就像它給了我2個readlines方法()由於某種原因幾乎就像「else if語句」給我2 ReadLines()如果用戶鍵入第二個或第三個選項

//Directions (Actions) You May Take: 

    public string forward = "forward"; 
    public string back = "back"; 
    public string left = "left"; 
    public string right = "right"; 


    public void closet() 
    { 
     Console.WriteLine("You open the door at the top of the basement staircase and it leads to what appears to be a closet?"); 
     Console.WriteLine("You can feel random clutter but it's still so dark. There is another door in front of you..."); 
     Console.WriteLine("Only 2 directions you can take. [BACK] or [FORWARD]"); 
     if (forward == Console.ReadLine()) 
     { 
      hallway(); 
     } 
     if (back == Console.ReadLine()) 
     { 
      Console.WriteLine("The door behind you to the basement is now locked... weird..."); 
     } 
     else 
     { 
      Console.WriteLine(wrong); 
     } 
    } 

    public void hallway() 
    { 
     Console.WriteLine("\nYou open the door in front of you and crawl out into what appears to be a hallway."); 
     Console.WriteLine("There are 3 direcitons you can take. [BACK] or [LEFT] or [RIGHT]"); 
     Console.WriteLine("What direction do you take?"); 
     if (left == Console.ReadLine()) 
     { 
      bathroom(); 
     } 

     if (right == Console.ReadLine()) 
     { 
      livingroom(); 
     } 
     else 
     { 
      Console.WriteLine(wrong); 
     } 

    } 

    public void bathroom() 
    { 
     Console.WriteLine("This is the bathroom"); 
    } 

    public void livingroom() 
    { 
     Console.WriteLine("This is the livingroom"); 
    } 
+1

我多次閱讀你的問題。但是找不到你正在問的關於 –

回答

0

您從控制檯多次拉出。你只想拉一次。 事情是這樣的,而不是:

var direction = Console.ReadLine() 
if (left == direction) 
{ 
    bathroom(); 
} 

if (right == direction) 
{ 
    livingroom(); 
} 
else 
{ 
    Console.WriteLine(wrong); 
} 
+0

謝謝!這真的解決了它! – user3080463

+0

@ user3080463謝謝!也許你現在已經知道了,但是一旦你從控制檯讀取數據,就沒有回頭路了。控制檯釋放線程並繼續工作。這就是爲什麼多次閱讀沒有給你你想要的結果。 – paqogomez

4

因爲你叫Console.ReadLine()兩次,每次都需要輸入。你只比較第二次和第二次的情況。你想要:

var inputString = Console.ReadLine(); 
if (inputString == forward) 
{ 
    hallway(); 
} 
else if (inputString == back) 
{ 
    Console.WriteLine("The door behind you to the basement is now locked... weird..."); 
} 

你需要爲兩組條件都這樣做。

+0

的問題,非常感謝你的回答!它幫助!我剛剛完成我的第一個編程課,所以我超級新。 – user3080463

+0

很好的答案+1。它驚人的30秒可以爲upvotes :) – paqogomez

0

那是因爲你有兩個到Console.ReadLine通話。您需要在if語句前移動一個ReadLine調用,並根據結果評估if-conditions。

相關問題