当前上下文中不存在名称“..”

时间:2017-09-20 08:07:51

标签: c#

我刚开始学习C#而且遇到了问题。

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This is a text adventure! <press space to continue>");
            Console.ReadKey();
            do
            {
                Console.WriteLine("A monster aproaches what do you do? <Attack,Flee>");
                string a = Console.ReadLine();
            } while(a != "Attack" && a != "Flee"); 

        }
    }
}

任何帮助都会有用。

4 个答案:

答案 0 :(得分:3)

我认为您应该将a声明为do块之外的字符串变量,如下所示:

string a = "";

do
{
    Console.WriteLine("A monster aproaches what do you do? <Attack,Flee>");
    a = Console.ReadLine();
} while (a != "Attack" && a != "Flee"); 

while倾向于Main方法范围,因此a必须存在Main才能在do块内分配。

答案 1 :(得分:0)

希望错误是&#39; a&#39;变量,修复就在这里......

&#39;一个&#39;变量必须在循环之前声明,你可以为&#39; a&#39;分配值。在循环内部进行迭代

    class Program
    {
     static void Main(string[] args)
     {
      Console.WriteLine("This is a text adventure! <press space to continue>");
      string a ;
      do
       {
       Console.WriteLine("A monster aproaches what do you do? <Attack,Flee>");
       a = Console.ReadLine();
     } while(a != "Attack" && a != "Flee"); 

    }
    }

答案 2 :(得分:0)

范围,如果a只到结束括号。在外面宣布它而不是使用它。

 string a = "";
        Console.WriteLine("This is a text adventure! <press space to continue>");
        Console.ReadKey();
        do
        {
            Console.WriteLine("A monster aproaches what do you do? <Attack,Flee>");
            a = Console.ReadLine();
        } while (a != "Attack" && a != "Flee");

答案 3 :(得分:-1)

你只需要做这个字符串a =“”;在使用readline设置字符串之前,您可以像尝试一样使用它。祝好运! :)