简体   繁体   中英

Console.ReadLine unexpected behaviour in else-if statement

I'm having some trouble with my console application. I want to check the user input and execute something depending on what the user wrote. My code looks something like this:

if(Console.ReadLine() == "ADD")
{
    //Add
} 
else if (Console.ReadLine() == "LIST")
{
    //DisplayList
}
else if (Console.ReadLine() == "SORT")
{
    //Sort
}
else 
{
    //DisplayErrorMsg
}

Now when i type LIST in the console, i get a line-break, and I have to type LIST again to get expected behaviour, and all following else-if statements just add another line-break. (example below) I've looked everywhere I can but I can't see what I've done wrong... Please help!

SORT
SORT
SORT
//Sorting...

You are invoking ReadLine multiple times and therefore you read multiple times from the stdin. Try the following:

var line = Console.ReadLine();

if (line == "ADD")
{
    //Add
} 
else if (line == "LIST")
{
    //DisplayList
}
else if (line == "SORT")
{
    //Sort
}
else 
{
    //DisplayErrorMsg
}

Try to get line in a string, and so test the string.

string line = Console.ReadLine();
if (line == "ADD")
{
    //Add
} 
else if (line == "LIST")
{
    //DisplayList
}
else if (line == "SORT")
{
    //Sort
}
else 
{
    //DisplayErrorMsg
}

Every time you call Console.ReadLine() it will wait for user input.

Assign the value returned from running Console.ReadLine() to a variable.

Then do your if, else checks on that variable.

var userInput = Console.ReadLine();

if(userInput == "ADD")
{
    //Add
} 
else if (userInput == "LIST")
{
    //DisplayList
}
else if (userInput == "SORT")
{
    //Sort
}
else 
{
    //DisplayErrorMsg
}
string readfromConsole = Console.ReadLine()
if(readfromConsole  == "ADD")
    {
        //Add
    } 
    else if (readfromConsole  == "LIST")
    {
        //DisplayList
    }
    else if (readfromConsole  == "SORT")
    {
        //Sort
    }
    else 
    {
        //DisplayErrorMsg
    }

The problem you are having is that Console.readLine does exactly what it says it reads a new line. So what this change does is it saves the first read and compares against that instead of reading a new line each time. I hoped this helped

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM