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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With