几乎就像“else if statement”给我2 ReadLines()如果用户键入第二个或第三个选项

时间:2013-12-08 18:29:03

标签: c# if-statement double readline

为什么每次我有第二个if/else if语句时,我必须输入第二个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");
    }

3 个答案:

答案 0 :(得分: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...");
}

您需要为两组条件执行此操作。

答案 1 :(得分:0)

您多次从控制台拉出来。你想只拉一次。 取而代之的是:

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

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

答案 2 :(得分:0)

这是因为你有两个Console.ReadLine调用。您需要在if语句前面移动一个ReadLine调用,并根据结果评估if条件。