Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
like image 851
Oscar Lundberg Avatar asked Dec 21 '25 01:12

Oscar Lundberg


2 Answers

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
}
like image 80
Nico Avatar answered Dec 23 '25 13:12

Nico


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
}
like image 29
Andrea Avatar answered Dec 23 '25 15:12

Andrea