我的程序中有一个错误,即使在查看了 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);
最佳答案
您正在声明 warOption
在你的do
里面 block ,但在 do
之外引用它阻止您的 while
声明:
do {
/* ... */
int warOption = Convert.ToInt32(stringWarOption);
/* ... */
} while (warOption != 1);
该变量未在该范围内定义。移动warOption
的声明到您的do
之前 block :
int warOption;
do {
/* ... */
warOption = Convert.ToInt32(stringWarOption);
/* ... */
} while (warOption != -1);
关于c# - 当前上下文中不存在该名称(变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32001241/