首页 > 解决方案 > Console.ReadLine 无法使用 .ToUpper 更改输入

问题描述

我正在创建一个选择你自己的冒险游戏,我正在尝试使用 .ToUpper(); 让用户输入更改为大写;但无论出于何种原因,如果输入尚未设置上限,则它会跳过 else if 语句并进入游戏的下一步。这是我的代码目前的样子。

Console.WriteLine("It begins on a cold rainy night. Your sitting in your room and hear a noise coming from down the hall. Do you go investigate?");

//First decision
Console.Write("Type YES or NO: ");
string noiseChoice = Console.ReadLine();
string capNoise = noiseChoice.ToUpper();
      

//First decision outcome      
if (noiseChoice == "NO")
{
    Console.WriteLine("Not much of an adventure if you don't leave your room!");
    Console.WriteLine("THE END.");
}
else if (noiseChoice == "YES")
{
    Console.WriteLine("You walk into the hallway and see a light coming from under a door down the hall.");
    Console.WriteLine("You walk towards it. Do you open it or knock?");
}

//Second decision
Console.Write("Type OPEN or KNOCK: ");
string doorChoice = Console.ReadLine();
string capDoor = doorChoice.ToUpper();

当提示输入 YES 或 NO 时,如果您输入 yes 或 no,它会跳到下一个 Console.Write(); 是 OPEN 或 KNOCK 类型。但是,如果输入是 YES 或 NO,它会根据需要继续执行 else if 语句。我对 C# 还很陌生,因此感谢您的帮助!

标签: c#user-inputconsole.readline

解决方案


您正在检查错误的变量。

在这里,您使用转换文本ToUpper()并将大写文本放入capNoise变量中

string capNoise = noiseChoice.ToUpper();
  

但是随后您需要检查具有大写文本的 capNoise,而是检查作为原始输入的 noiseChoice。

if (noiseChoice == "NO")

因此,您要么需要将 ToUpper() 结果存储在noiseChoise 中。

noiseChoice= noiseChoice.ToUpper();

或检查 capNoise

if (capNoise == "NO")

推荐阅读