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 trialAnkit Biswas
280 PointsI got stuck in a challenge please help me Code isn't running because of compiler error. If else problem.
Add more input validation to the program by printing "You must enter a positive number." if the user enters a negative number.
Add an if/else conditional statement just after parsing the user's provided input to an integer Write a conditional expression to ensure that the remainder of the code in the try block is only executed if the user provides a non-negative number If the user enters a negative number, output to the console the message "You must enter a positive number."?
using System;
namespace Treehouse.CodeChallenges
{
class Program
{
static void Main()
{
Console.Write("Enter the number of times to print \"Yay!\": ");
string input = Console.ReadLine();
int count = int.Parse(input);
if(count > 0)
{
try
{
int i = 0;
while(i < count)
{
i += 1;
Console.WriteLine("Yay!");
}
}
}
else
{
Console.WriteLine("You must enter a positive number.");
}
catch(FormatException exception)
{
Console.WriteLine("You must enter a whole number.");
}
}
}
}
2 Answers
Steven Parker
231,236 PointsThe "try" and "catch" must be in the same code block and have no other code in between. In the code shown here, neither of those is true.
Formatting the code so that each block is indented would make it easier to see that the "try" is inside the "if" conditional block, but the "catch" comes after the "else" block.
You can restructure the code so that the "if" and "else" are both completely inside the "try" block to fix this.
Khaidem Sandip Singha
Front End Web Development Techdegree Student 17,574 PointsHere is the complete solution to the challenge
using System;
namespace Treehouse.CodeChallenges
{
class Program
{
static void Main()
{
Console.Write("Enter the number of times to print \"Yay!\": ");
string input = Console.ReadLine();
try{
int count = int.Parse(input);
if(count > 0){
int i = 0;
while(i < count)
{
i += 1;
Console.WriteLine("Yay!");
}
} else{
Console.WriteLine("You must enter a positive number.");
}
} catch(FormatException){
Console.WriteLine( "You must enter a whole number.");
}
}
}
}