Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Basics (Retired) Perfect Variable Scope

Samuel Joseph
Samuel Joseph
5,406 Points

I am stuck trying to figure out what they want for this section. My try/catch seems to be off and unsure how to fix it.

I am stuck trying to figure out what they want for this section. My try/catch seems to be off and unsure how to fix it.

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {            
            input = Console.ReadLine();

            if (input == "quit")
            {
                string output = "Goodbye.";
            }
            else
            {
                try
                {

                string output = "You entered " + input + ".";
            }

            Console.WriteLine(output);
                }

            catch(FormatException)
            {
                Console.WriteLine("That is not a valid input");
                continue;
            }

        }
    }
}

1 Answer

Chris Jones
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Chris Jones
Java Web Development Techdegree Graduate 23,933 Points

Hey Samuel!

There's no need for a try-catch block in this case. The code challenge is designed to test your understanding of variable scope.

There are two variables in the main method: input and output. You'll need to make a couple changes to pass the code challenge. Try this:

using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {            
            string input = Console.ReadLine();
            string output;

            if (input == "quit")
            {
                output = "Goodbye.";
            }
            else
            {
                output = "You entered " + input + ".";
            }

            Console.WriteLine(output);
        }
    }
}

Notice how input is declared and initialized before the if-else statement. You need to at least declare a variable, which means to give it a type (int, string, boolean, etc).

You also need to declare the output variable, which is what I'm doing when I write string output;. However, we don't need to initialize the output variable yet, because that value we initialize it to depends on the logic in the if-else statement.

I hope that helps! Let me know if you have any more questions!