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

时间:2019-05-04 19:25:56

标签: c# if-statement user-input

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

我的if else语句遇到麻烦。我似乎无法弄清楚他们是否在摇前输入了一个问题。

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;
    }
    }

1 个答案:

答案 0 :(得分:1)

问题的原因是您没有初始化userAnswer,这就是为什么当用户第一次键入 S 时,userAnswer变量具有一个很可能是!=null的随机值。

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