c# - If 语句不能正常工作不会通过 If 语句 C#
问题描述
我正在cmd中制作一个魔术8球。我想问用户是否愿意。我希望程序继续提问,直到用户选择字母 E。如果他们在提问之前尝试摇晃,那么他们会收到错误消息。
我遇到的问题是,当您输入 A 时,您将输入一个问题。然后当我输入 S 之后,我收到搜索 RAM 的错误消息,它没有调用我的摇动方法。
所以现在发生的事情是我写了“A”。然后我输入我的问题,选项再次出现。一旦选项再次出现,我选择“S”,然后出现 ram 语句而不是转到 else 语句。我需要它去摇动方法,然后我可以输入“G”来得到我的答案。
public static string userAnswer = "";
static void Main(string[] args)
{
Console.WriteLine("Main program!");
Console.WriteLine("Welcome to the Magic 8 Ball");
Console.WriteLine("What would you like to do?");
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
Magic8Ball_Logic.Magic8Ball ball = new Magic8Ball_Logic.Magic8Ball();
string input = Console.ReadLine().ToUpper();
do
{
if (input == "S")
{
if (userAnswer != null)
{
Console.WriteLine("Searching the Mystic Realms(RAM) for the answer");
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
input = Console.ReadLine();
}
else
{
//Call Method Shake()
ball.Shake();
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
input = Console.ReadLine();
}
}
else if (input == "A")
{
userAnswer = Console.ReadLine();
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
input = Console.ReadLine();
}
else if (input == "G")
{
if (userAnswer != null)
{
Console.WriteLine("Please Enter A Question Before Asking For An Answer.");
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
input = Console.ReadLine();
}
else
{
//Call Method GetAnswer()
ball.GetAnswer();
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
input = Console.ReadLine();
}
}
} while (input != "E");
}
解决方案
您正在string userAnswer = "";
声明中设置。但是..如果您正在检查它,if (userAnswer != null)
但是...它永远不会为空
您应该检查if (userAnswer != "")
因为如果字符串的值null
与空字符串不同""
推荐阅读
- java - File.exists() 有效,但 Files.readAllBytes() 因 NoSuchFileException 而失败
- typescript - 打字稿:映射类型中的索引签名
- c++ - C++:结构的默认构造函数不起作用?
- android - 通过删除 Reloading 状态并仅使用 Loading 状态来简化 ViewState
- python - 通过匹配模式获取多个子字符串
- ruby-on-rails - 将 Rails + mongoid 与嵌入式 shopify 应用程序集成时出现问题
- javascript - 如何在 React Native 上一开始就关闭键盘
- azure-devops - Azure devops 的 Power BI 报告
- mysql - SQL:直接从连接中获取顶部元素
- azure-functions - Azure 函数:函数“测试”的侦听器无法启动。请验证 Azure 存储模拟器是否正在运行