如何解决“名称***在当前上下文中不存在”的错误?

时间:2019-03-12 17:14:46

标签: c# try-catch

我试图在此代码中添加一个Try / Catch块,但我不知道要进行哪些更改才能使其正常工作。

有什么建议吗? 出现此错误:

  

“错误CS0103名称'fahrenheit'在当前上下文中不存在”

class Program
{
    static int FahrenheitToCelsius(int fahrenheit)
    {
        int celsius = ((fahrenheit - 32) * 5) / 9;
        return celsius;
    }

    static void Main(string[] args)
    {
        int celsius;

        Console.WriteLine("Hello! Welcome to the sauna!");
        Console.WriteLine();
        Console.WriteLine("Please enter your desired degrees in Fahrenheit: ");

        do
        {
            try
            {
                int fahrenheit = Convert.ToInt32(Console.ReadLine());
            }
            catch (FormatException)
            {
            }

            celsius = FahrenheitToCelsius(fahrenheit);
            Console.WriteLine("The sauna is now set to " + fahrenheit + 
                " degrees Fahrenheit, which equals to " + celsius + " degrees Celsius.");

            if (celsius < 25)
            {
                Console.WriteLine("Way too cold! Turn the heat up: ");
            }
            else if (celsius < 50)
            {
                Console.WriteLine("Too cold, turn the heat up: ");
            }
            else if (celsius < 73)
            {
                Console.WriteLine("Just a little bit too cold, turn the heat up a " + 
                    "little to reach the optimal temperature: ");
            }
            else if (celsius == 75)
            {
                Console.WriteLine("The optimal temperature has been reached!");
            }
            else if (celsius > 77)
            {
                Console.WriteLine("Too hot! Turn the heat down: ");
            }
            else
                Console.WriteLine("The sauna is ready!");
            {
            }
        } while (celsius < 73 || 77 < celsius);

        Console.ReadLine();
    }
}

2 个答案:

答案 0 :(得分:0)

您可以做一些不同的事情。

  1. 您可以将代码的顶部放在int celcisus附近,也可以放在int fahrenheit
  2. 您可以将所有代码都放在try中,如果有任何失败,请注意。

答案 1 :(得分:0)

看下面的代码:

try
{
    int fahrenheit = Convert.ToInt32(Console.ReadLine());
}

fahrenheit仅存在于try {}块中,当您稍后尝试使用它时。将其移至父范围:

int fahrenheit;
while (true)
{
   try
   {
        fahrenheit = Convert.ToInt32(Console.ReadLine());
        break;
   }
   catch (FormatException)
   {
      continue;
   }
}
celsius = FahrenheitToCelsius(fahrenheit);

请注意,对于FormatException,没有什么可计算的,因此我在while (true)块中添加了continuecatch的循环。另外,我建议在这里使用Int32.TryParse方法,它将以bool的形式返回解析结果,而不是引发异常。

相关问题