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 trialCharles Szvetecz
1,278 PointsNeed help with Task #1 in the code challenge after the "try" and "catch" module in c# Basic.
I can't seem to correctly answer the code challenge. Can someone please provide correct answer so I can learn and move on with peace of mind.
using System;
namespace Treehouse.CodeChallenges
{
class Program
{
static void Main()
{
input = Console.ReadLine();
if (input == "quit")
{
string output = "Goodbye.";
}
else
{
string output = "You entered " + input + ".";
}
Console.WriteLine(output);
}
}
}
1 Answer
Jason Anders
Treehouse Moderator 145,860 PointsHey Charles,
This challenge is all about "scope" of variables. If a variable is declared inside of a block of code, it cannot be accessed outside that block of code.
But first, you will need to declare the input
variable, as it is now, it is just being assigned a value (the user input).
Second you will need to declare an empty output
variable once outside of the if/else block. Then inside of the if/else block, remove the declaration and just assign the new value based on the conditional. Remember that variables can be assigned a correct value as many times and in as many places as you want.
And that's all that needs to be refactored. Below is the corrected code for you to review. If it still doesn't make sense, I strongly suggest reviewing scope
until it makes sense, because variable scope is extremely important in OOP.
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);
}
}
}
Keep Coding! :)