简体   繁体   English

C# - 当前上下文中不存在该名称

[英]C# - The name does not exist in the current context

I started my C# study this week and got trouble with this assignment. 我本周开始进行C#学习,并且在这项任务中遇到了麻烦。
The expensive book they made us buy does a poor job explaining this. 他们让我们买的这本昂贵的书很难解释这一点。
We have to use, If, Else, While and Do in this assignment. 我们必须在这个任务中使用,If,Else,While和Do.

I get this error, The name 'answer' does not exist in the current context. 我收到此错误,当前上下文中不存在名称“answer”。
What am I doing wrong? 我究竟做错了什么?

int question = 25;

do
{
    Console.Write("Guess the number: ");
    string strAnswer = Console.ReadLine();
    int answer = Convert.ToInt32(strAnswer);

    if (answer < question)
    {
        Console.WriteLine("Too low, guess again. ");
    }
    else if (answer > question)
    {
        Console.WriteLine("Too high, guess again. ");
    }
}

while (answer != question);
Console.Write("Correct!");

Try this, answer defined in different scope, you need define it at higher scope, 试试这个,在不同范围内定义的答案,你需要在更高的范围内定义,

 int question = 25;
 int answer = 0;
 do
 {
     Console.Write("Guess the number: ");
     string strAnswer = Console.ReadLine();
     answer = Convert.ToInt32(strAnswer);

     if (answer < question)
     {
         Console.WriteLine("Too low, guess again. ");
     }
     else if (answer > question)
     {
         Console.WriteLine("Too high, guess again. ");
     }
  }

  while (answer != question);
     Console.Write("Correct!");

answer is declared inside the scope of the do block. answer是在do块的范围内声明的。 It will not be accessible outside ofthat block (in the while condition). 它不会在该块之外访问(在while条件下)。 Try: 尝试:

int question = 25;
int answer;

do
{
   Console.Write("Guess the number: ");
   string strAnswer = Console.ReadLine();
   answer = Convert.ToInt32(strAnswer);

   if (answer < question)
   {
       Console.WriteLine("Too low, guess again. ");
   }
   else if (answer > question)
   {
       Console.WriteLine("Too high, guess again. ");
   }
}
while (answer != question);

Your answer variable is out of scope. 你的答案变量超出了范围。 Your declaring answer inside the DO braces, but trying to access it outside in your while loop 您在DO括号内声明的答案,但尝试在while循环中访问它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM