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 trialAustin Clark
384 PointsAdd input validation
Hello,
Im trying to get the console to print "You must enter a valid number." when the user enters something that is NOT an integer. Attached is my code, but I cant seem to figure out how to get it working.
Console.Write("Enter the number of times to print \"Yay!\": "); var total = int.Parse(Console.ReadLine()); int counter=0;
while (counter < total)
{
Console.WriteLine("Yay!");
counter ++ ;
}
catch (FormatException)
{
Console.WriteLine("You must enter a whole number.");
}
Console.Readline();
}
}
}
using System;
namespace Treehouse.CodeChallenges
{
class Program
{
static void Main()
{
Console.Write("Enter the number of times to print \"Yay!\": ");
var total = int.Parse(Console.ReadLine());
int counter=0;
while (counter < total)
{
Console.WriteLine("Yay!");
counter ++ ;
}
catch (FormatException)
{
Console.WriteLine("You must enter a whole number.");
}
Console.Readline();
}
}
}
1 Answer
Dale Severude
Full Stack JavaScript Techdegree Graduate 71,350 PointsHi Austin,
Your code is missing a TRY block. You can't catch an exception without a TRY block first.
Also, something is funky with your Console.ReadLine() at the end. It is not needed for the challenge. Check the preview button to make sure your code has no compile errors.
I added a TRY block and removed the Console.ReadLine() and your code works.