Almost as though "else if statement" is giving me 2 ReadLines() If the user types the second or third options [closed]

StackOverflow https://stackoverflow.com/questions/20457222

Question

Why is it that every time I have a second if/else if statement, I have to enter whatever the second if condition is, twice? Almost as though its giving me 2 ReadLines() for some reason

//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");
    }
Was it helpful?

Solution 2

You are pulling from the console multiple times. You want to only pull once. Something like this instead:

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

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

OTHER TIPS

Because you call Console.ReadLine() twice and each time it takes input. You only compare the second time against the second condition. You want:

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...");
}

You'll need to do this for both sets of conditionals.

That is because you have two Console.ReadLine-calls. You need to move a single ReadLine call in front of the if-statements and evaluate the if-conditions against the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top