【发布时间】:2022-08-19 21:32:53
【问题描述】:
我正在制作一款文字冒险游戏,但我一直在制作一个 y/n 选项。
这是我的代码。顺便说一句,我对编码太陌生了,就像一晚新的一样。
Console.WriteLine(\"Are You Ready For The Day My Lord [y/n]\");
Console.ReadLine();
对不起,如果这太容易了。
-
您只想检查玩家输入的是“y”还是“n”?
我正在制作一款文字冒险游戏,但我一直在制作一个 y/n 选项。
这是我的代码。顺便说一句,我对编码太陌生了,就像一晚新的一样。
Console.WriteLine(\"Are You Ready For The Day My Lord [y/n]\");
Console.ReadLine();
对不起,如果这太容易了。
你可以用这样的东西
Console.WriteLine("Are You Ready For The Day My Lord [y/n]");
string yesNo = Console.ReadLine(); //get the answer
if(yesNo == "y") //check the answer
Console.WriteLine("You are ready."); //write something for option y
else
Console.WriteLine("You are NOT ready."); //write something for other option
【讨论】:
我建议使用 string.Equals 来比较字符串,这样这样的东西应该可以正常工作:
Console.WriteLine("Are You Ready For The Day My Lord [y/n]");
string userInput = Console.ReadLine();
if(string.Equals(userInput, "y"))
{
Console.WriteLine("You answered yes");
}
else
{
Console.WriteLine("You answered no");
}
如果你只想要“y”或“n”
【讨论】:
== 更啰嗦,而且我看不到任何好处......
string.Equals(userInput, "y", StringComparison.CurrentCultureIgnoreCase) 这样的不区分大小写的比较,这个变体可能会很有趣
像这样的事情可能是你的情况
ConsoleKeyInfo k = Console.ReadKey();
if (k.Key.ToString() == "y")
{
// do what you need for yes
}
else
{
// presses something other then Y
}
【讨论】:
听起来你会经常这样做,所以也许将这些事情包装在一个帮助类中
public static class Prompt
{
public bool GetYesNo(string input)
{
Console.Writeline(input + " [y/n]");
var result = Console.ReadLine().ToLower();
if(result == "y") return true;
if(result == "n") return false;
Console.WriteLine("Invalid input");
return GetYesNo(input);
}
}
然后在您的控制台应用程序中:
var ready = Prompt.GetYesNo("Are You Ready For The Day My Lord");
if(ready)
{
// do something
}
【讨论】:
我正在使用此代码。
Console.WriteLine("Are You Ready For The Day My Lord [y/n]");
string userInput = Console.ReadLine();
if(string.Equals(userInput, "y"))
{
Console.WriteLine("You answered yes");
}
else
{
Console.WriteLine("You answered no");
}
谢谢大家的帮助。
【讨论】:
这应该有效:
Console.WriteLine("Are You Ready For The Day My Lord [y/n]");
string currOption = Console.ReadLine();
if (currOption == "Y" || currOption == "y"){
Console.WriteLine("You answered yes");
}
else if(currOption == "N" || currOption == "n"){
Console.WriteLine("You answered no");
}
else{
Console.WriteLine("Invalid Input");
}
希望它有效!
【讨论】: