[英]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. 现在当我在控制台中键入LIST时,我得到一个换行符,我必须再次键入LIST以获得预期的行为,并且所有后续else-if语句只是添加另一个换行符。 (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. 您多次调用ReadLine
,因此您从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. 每次调用Console.ReadLine()
它都会等待用户输入。
Assign the value returned from running Console.ReadLine()
to a variable. 将运行Console.ReadLine()
返回的值分配给变量。
Then do your if, else checks on that variable. 然后执行if,else检查该变量。
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. 您遇到的问题是Console.readLine完全按照它所说的读取新行。 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 我希望这有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.