0

I'm trying to add a Try/Catch block to this code but I can't figure out what to change to make it work..

Any suggestions? Getting this error:

"Error CS0103 The name 'fahrenheit' does not exist in the current context"

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();
    }
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
Chrilla
  • 21
  • 1
  • 6
  • Just define `farenheit` outside the scope of the `try` block if you want to access it outside that block. Perhaps where you define `celcius`? – Rufus L Mar 12 '19 at 17:30
  • That being said, you should really use `int.TryParse` rather than exception handling to validate the user input. – Rufus L Mar 12 '19 at 17:34

4 Answers4

1

Look at this code:

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

fahrenheit will exist only inside try {} block while you try to use it later. Move it to parent scope:

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

Note that in case of FormatException there is nothing to calculate, so I added while (true) loop with continue inside catch block. Also I recommend to use Int32.TryParse method here, it will return parsing result as bool instead of raising exception.

ingvar
  • 4,169
  • 4
  • 16
  • 29
  • Oh, I see! Changed the code like you said, now I'm getting this error instead: Error CS0165 Use of unassigned local variable 'celsius' – Chrilla Mar 12 '19 at 17:31
  • yeah, in this case on first run `celsius` wasn't set but it used in `while (celsius < 73 || 77 < celsius);` See my updated answer – ingvar Mar 12 '19 at 17:34
  • Thanks! Solved the problem! – Chrilla Mar 12 '19 at 18:09
1

There are a couple of problems here. The main one is that Fahrenheit needs to be declared outside the try block since you're using it outside that block (variables are scoped to the block in which they're declared). Moving it to where you define celsius seems logical, although it's usually best to declare variables at the innermost scope required.

The second thing is that you should use the int.TryParse method to validate the user input rather than a try/catch block. It performs much better and is cleaner, more intentional code. Read the answer to this question for more information.

This method returns true if successful, and takes in a string to parse (we use the return value of Console.ReadLine() directly below), and an out parameter that will be set to the converted integer if successful.

These changes might look something like:

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

    Console.WriteLine("Hello! Welcome to the sauna!\n");

    do
    {
        // Use a loop with TryParse to validate user input; as long as
        // int.TryParse returns false, we continue to ask for valid input
        int fahrenheit;
        do
        {
            Console.Write("Please enter your desired degrees in Fahrenheit: ");

        } while (!int.TryParse(Console.ReadLine(), out fahrenheit));

        celsius = FahrenheitToCelsius(fahrenheit);

        // Rest of loop code omitted...

    } while (celsius < 73 || 77 < celsius);

    Console.ReadLine();
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • Thanks for clearing that out, had to use try/catch on this course, but will definetely use int.TryParse in the future! – Chrilla Mar 12 '19 at 18:11
0

You could do a few different things.

  1. You could put at the top of the code near int celcisus also int fahrenheit
  2. You could put all the code in the try and if anything failed it'd go to the catch.
Jamie R Rytlewski
  • 1,172
  • 9
  • 22
0

Your have to declare the variable in the outer scope handle the exception in order to have a calid C# program.

This way, you'll end up on your variable assigned when the conversion is successful, otherwise you simply reask the user the value:

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
        {
            // you have to declare the variable out of the scope
            int fahrenheit;
            try
            {
                fahrenheit = Convert.ToInt32(Console.ReadLine());
            }
            catch (FormatException)
            {
                // and here you have to handle the exception
                Console.WriteLine("Invalid value.");
                continue;                    
            }

            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();

    }
}
Yennefer
  • 5,704
  • 7
  • 31
  • 44