名称(变量)在当前上下文中不存在

时间:2015-08-14 02:06:47

标签: c# loops do-while

我的程序中有一个我似乎无法解决的错误 - 即使在查看Stack Overflow和Google上的问题之后。我的程序抛出异常,“当前上下文中不存在名称(变量)。”

do {
      Console.WriteLine("");
      Console.WriteLine("Before you begin, chose a battle to join!");
      Console.WriteLine("1. Battle of Copenhagen - 1801");
      Console.WriteLine("2. Battle of Morton's Ford - 1864");
      Console.WriteLine("3. Battle of Schuinshoogte - 1881");
      Console.WriteLine("4. Battle of Kufit - 1885");
      Console.WriteLine("5. Invasion of Normandy - 1944");

      String stringWarOption = Console.ReadLine();
      int warOption = Convert.ToInt32(stringWarOption);

      switch (warOption){
          case 1:
              //continue all code here
              Console.WriteLine("Loading the Battle of Copenhagen - 1801.");
              break;
          case 2:
              Console.WriteLine("This war is locked, however you can read up about it here: ");
              Console.WriteLine("https://en.wikipedia.org/wiki/List_of_battles_1801%E2%80%931900");
              break;
          case 3:
              Console.WriteLine("This war is locked, however you can read up about it here: ");
               Console.WriteLine("https://en.wikipedia.org/wiki/List_of_battles_1801%E2%80%931900");
              break;
          case 4: 
              Console.WriteLine("This war is locked, however you can read up about it here: ");
              Console.WriteLine("https://en.wikipedia.org/wiki/List_of_battles_1801%E2%80%931900");
              break;
          case 5:
              Console.WriteLine("This war is locked, however you can read up about it here: ");
              Console.WriteLine("https://en.wikipedia.org/wiki/Invasion_of_Normandy");
              break;
          default:
              break;
      }
  }
  while (warOption != 1);

1 个答案:

答案 0 :(得分:4)

您在warOption块中声明do,但在do声明中while块之外引用它:

do {
    /* ... */
    int warOption = Convert.ToInt32(stringWarOption);
    /* ... */
} while (warOption != 1);

该范围内未定义变量。将warOption的声明移至do块之前:

int warOption;

do {
    /* ... */
    warOption = Convert.ToInt32(stringWarOption);
    /* ... */
} while (warOption != -1);