C#查看用户是否在命令行中输入文本



我希望用户输入问题。他们可以输入" A"并提出问题。如果他们键入" S",则它将摇晃答案列表。如果他们在输入问题之前先键入" S",则将收到错误消息。

我在其他语句中遇到麻烦。我似乎无法弄清楚他们是否在摇晃之前就输入问题。

program.cs:

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();
     public string userAnswer
     do
     {
        if (input == "S")
        {
            if (userAnswer != null)
            {
                Console.WriteLine("Searching the Mystic Realms(RAM) for the answer");
            }
            else
            {
                //Call Method Shake()
            }
        }
        else if (input == "A") {
                userAnswer = Console.ReadLine();
        }
        else if (input == "G") {
               //Call Method GetAnswer()
        }
    } while (input != "E");
}

magic8ball.cs

public void Shake()
    {
        //picking the index of the answer to show the user
        Random r = new Random();
        int index = r.Next(_answers.Count);
        randomString = _answers[index];
    }
    public string GetAnswer()
    {
        //using the index picked by shake to return the answer
        //return "";
        return randomString;
    }
    }

问题的原因是您没有初始化 userAnswer,这就是为什么当用户类型 s 首次 userAnswer变量时,这就是为什么一个随机值,很可能是!=null

修复很容易:用null初始化userAnswer

相关内容

  • 没有找到相关文章

最新更新